blob: ed16a37a15de1c8c5c1360d9d48d418f2c20b6c8 [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 Tate9bbc21a2009-06-10 20:23:25 -070059import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070060import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070061
Christopher Tate6785dd82009-06-18 15:58:25 -070062import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070063import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070064
Christopher Tatecde87f42009-06-12 12:55:53 -070065import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070066import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070067import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070068import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070069import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070070import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070071import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040072import java.util.ArrayList;
73import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070074import java.util.HashSet;
75import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070076import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070077
78class BackupManagerService extends IBackupManager.Stub {
79 private static final String TAG = "BackupManagerService";
80 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070081
Christopher Tate49401dd2009-07-01 12:34:29 -070082 // How often we perform a backup pass. Privileged external callers can
83 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070084 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070085
Christopher Tate8031a3d2009-07-06 16:36:05 -070086 // The amount of time between the initial provisioning of the device and
87 // the first backup pass.
88 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
89
Christopher Tateb6787f22009-07-02 17:40:45 -070090 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070091 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070092 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070093 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070094 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070095
Dan Egnorbb9001c2009-07-27 12:20:13 -070096 // Event tags -- see system/core/logcat/event-log-tags
97 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
98 private static final int BACKUP_START_EVENT = 2821;
99 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
100 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
101 private static final int BACKUP_PACKAGE_EVENT = 2824;
102 private static final int BACKUP_SUCCESS_EVENT = 2825;
103
104 private static final int RESTORE_START_EVENT = 2830;
105 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
106 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
107 private static final int RESTORE_PACKAGE_EVENT = 2833;
108 private static final int RESTORE_SUCCESS_EVENT = 2834;
109
Christopher Tatec7b31e32009-06-10 15:49:30 -0700110 // Timeout interval for deciding that a bind or clear-data has taken too long
111 static final long TIMEOUT_INTERVAL = 10 * 1000;
112
Christopher Tate487529a2009-04-29 14:03:25 -0700113 private Context mContext;
114 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700115 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700116 private PowerManager mPowerManager;
117 private AlarmManager mAlarmManager;
118
Christopher Tate73e02522009-07-15 14:18:26 -0700119 boolean mEnabled; // access to this is synchronized on 'this'
120 boolean mProvisioned;
121 PowerManager.WakeLock mWakelock;
122 final BackupHandler mBackupHandler = new BackupHandler();
123 PendingIntent mRunBackupIntent;
124 BroadcastReceiver mRunBackupReceiver;
125 IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700126 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700127 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700128 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700129 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700130 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700131 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700132 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700133
Christopher Tate181fafa2009-05-14 11:12:14 -0700134 BackupRequest(ApplicationInfo app, boolean isFull) {
135 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700136 fullBackup = isFull;
137 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700138
139 public String toString() {
140 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
141 }
Christopher Tate46758122009-05-06 11:22:00 -0700142 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400143 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700144 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700145 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700146
147 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700148 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700149
150 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700151 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700152
Christopher Tate043dadc2009-06-02 16:11:00 -0700153 // The thread performing the sequence of queued backups binds to each app's agent
154 // in succession. Bind notifications are asynchronously delivered through the
155 // Activity Manager; use this lock object to signal when a requested binding has
156 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700157 final Object mAgentConnectLock = new Object();
158 IBackupAgent mConnectedAgent;
159 volatile boolean mConnecting;
Christopher Tate043dadc2009-06-02 16:11:00 -0700160
Christopher Tatec7b31e32009-06-10 15:49:30 -0700161 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700162 final Object mClearDataLock = new Object();
163 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700164
Christopher Tate91717492009-06-26 21:07:13 -0700165 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700166 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700167 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700168 String mCurrentTransport;
169 IBackupTransport mLocalTransport, mGoogleTransport;
170 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700171
Christopher Tate73e02522009-07-15 14:18:26 -0700172 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700173 public IBackupTransport transport;
174 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700175 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700176
Dan Egnor156411d2009-06-26 13:20:02 -0700177 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700178 transport = _transport;
179 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700180 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181 }
182 }
183
Christopher Tate73e02522009-07-15 14:18:26 -0700184 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700185 public IBackupTransport transport;
186 public PackageInfo packageInfo;
187
188 ClearParams(IBackupTransport _transport, PackageInfo _info) {
189 transport = _transport;
190 packageInfo = _info;
191 }
192 }
193
Christopher Tate5cb400b2009-06-25 16:03:14 -0700194 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700195 File mBaseStateDir;
196 File mDataDir;
197 File mJournalDir;
198 File mJournal;
199 RandomAccessFile mJournalStream;
200
201 // Keep a log of all the apps we've ever backed up
202 private File mEverStored;
203 private RandomAccessFile mEverStoredStream;
204 HashSet<String> mEverStoredApps = new HashSet<String>();
205
Christopher Tateaa088442009-06-16 18:25:46 -0700206
Christopher Tate487529a2009-04-29 14:03:25 -0700207 public BackupManagerService(Context context) {
208 mContext = context;
209 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700210 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700211
Christopher Tateb6787f22009-07-02 17:40:45 -0700212 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
213 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
214
Christopher Tate22b87872009-05-04 16:41:53 -0700215 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700216 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700217 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700218 // !!! TODO: mProvisioned needs to default to 0, not 1.
219 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700220 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700221 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700222 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700223
Christopher Tateb6787f22009-07-02 17:40:45 -0700224 mRunBackupReceiver = new RunBackupReceiver();
225 mRunBackupFilter = new IntentFilter();
226 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
227 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
228
229 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
230 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
231 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
232 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
233 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
234
Christopher Tatecde87f42009-06-12 12:55:53 -0700235 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700236 mJournalDir = new File(mBaseStateDir, "pending");
237 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700238 makeJournalLocked(); // okay because no other threads are running yet
239
Christopher Tate73e02522009-07-15 14:18:26 -0700240 // Set up the various sorts of package tracking we do
241 initPackageTracking();
242
Christopher Tateabce4e82009-06-18 18:35:32 -0700243 // Build our mapping of uid to backup client services. This implicitly
244 // schedules a backup pass on the Package Manager metadata the first
245 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700246 synchronized (mBackupParticipants) {
247 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700248 }
249
Dan Egnor87a02bc2009-06-17 02:30:10 -0700250 // Set up our transport options and initialize the default transport
251 // TODO: Have transports register themselves somehow?
252 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700253 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700254 ComponentName localName = new ComponentName(context, LocalTransport.class);
255 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700256
Christopher Tate91717492009-06-26 21:07:13 -0700257 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700258 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
259 Settings.Secure.BACKUP_TRANSPORT);
260 if ("".equals(mCurrentTransport)) {
261 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700262 }
Christopher Tate91717492009-06-26 21:07:13 -0700263 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
264
265 // Attach to the Google backup transport. When this comes up, it will set
266 // itself as the current transport because we explicitly reset mCurrentTransport
267 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700268 Intent intent = new Intent().setComponent(new ComponentName(
269 "com.google.android.backup",
270 "com.google.android.backup.BackupTransportService"));
271 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700272
Christopher Tatecde87f42009-06-12 12:55:53 -0700273 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700274 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700275 parseLeftoverJournals();
276
Christopher Tateb6787f22009-07-02 17:40:45 -0700277 // Power management
278 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
279
280 // Start the backup passes going
281 setBackupEnabled(areEnabled);
282 }
283
284 private class RunBackupReceiver extends BroadcastReceiver {
285 public void onReceive(Context context, Intent intent) {
286 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
287 if (DEBUG) Log.v(TAG, "Running a backup pass");
288
289 synchronized (mQueueLock) {
290 // acquire a wakelock and pass it to the backup thread. it will
291 // be released once backup concludes.
292 mWakelock.acquire();
293
294 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
295 mBackupHandler.sendMessage(msg);
296 }
297 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700298 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700299 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700300
Christopher Tate73e02522009-07-15 14:18:26 -0700301 private void initPackageTracking() {
302 if (DEBUG) Log.v(TAG, "Initializing package tracking");
303
Christopher Tatee97e8072009-07-15 16:45:50 -0700304 // Keep a log of what apps we've ever backed up. Because we might have
305 // rebooted in the middle of an operation that was removing something from
306 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700307 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700308 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700309 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700310 // If there are previous contents, parse them out then start a new
311 // file to continue the recordkeeping.
312 if (mEverStored.exists()) {
313 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
314 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700315
Christopher Tatedfec20b2009-08-03 15:38:09 -0700316 // parse its existing contents
317 mEverStoredStream.seek(0);
318 temp.seek(0);
319 try {
320 while (true) {
321 PackageInfo info;
322 String pkg = mEverStoredStream.readUTF();
323 try {
324 info = mPackageManager.getPackageInfo(pkg, 0);
325 mEverStoredApps.add(pkg);
326 temp.writeUTF(pkg);
327 if (DEBUG) Log.v(TAG, " + " + pkg);
328 } catch (NameNotFoundException e) {
329 // nope, this package was uninstalled; don't include it
330 if (DEBUG) Log.v(TAG, " - " + pkg);
331 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700332 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700333 } catch (EOFException e) {
334 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700335 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700336
Christopher Tatedfec20b2009-08-03 15:38:09 -0700337 // Once we've rewritten the backup history log, atomically replace the
338 // old one with the new one then reopen the file for continuing use.
339 temp.close();
340 mEverStoredStream.close();
341 tempProcessedFile.renameTo(mEverStored);
342 }
343 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700344 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700345 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700346 } catch (IOException e) {
347 Log.e(TAG, "Unable to open known-stored file!");
348 mEverStoredStream = null;
349 }
350
Christopher Tatee97e8072009-07-15 16:45:50 -0700351 // If we were in the middle of removing something from the ever-backed-up
352 // file, there might be a transient "processed.new" file still present.
353 // We've reconstructed a coherent state at this point though, so we can
354 // safely discard that file now.
355 if (tempProcessedFile.exists()) {
356 tempProcessedFile.delete();
357 }
358
Christopher Tate73e02522009-07-15 14:18:26 -0700359 // Register for broadcasts about package install, etc., so we can
360 // update the provider list.
361 IntentFilter filter = new IntentFilter();
362 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
363 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
364 filter.addDataScheme("package");
365 mContext.registerReceiver(mBroadcastReceiver, filter);
366 }
367
Christopher Tatecde87f42009-06-12 12:55:53 -0700368 private void makeJournalLocked() {
369 try {
370 mJournal = File.createTempFile("journal", null, mJournalDir);
371 mJournalStream = new RandomAccessFile(mJournal, "rwd");
372 } catch (IOException e) {
373 Log.e(TAG, "Unable to write backup journals");
374 mJournal = null;
375 mJournalStream = null;
376 }
377 }
378
379 private void parseLeftoverJournals() {
380 if (mJournal != null) {
381 File[] allJournals = mJournalDir.listFiles();
382 for (File f : allJournals) {
383 if (f.compareTo(mJournal) != 0) {
384 // This isn't the current journal, so it must be a leftover. Read
385 // out the package names mentioned there and schedule them for
386 // backup.
387 try {
388 Log.i(TAG, "Found stale backup journal, scheduling:");
389 RandomAccessFile in = new RandomAccessFile(f, "r");
390 while (true) {
391 String packageName = in.readUTF();
392 Log.i(TAG, " + " + packageName);
393 dataChanged(packageName);
394 }
395 } catch (EOFException e) {
396 // no more data; we're done
397 } catch (Exception e) {
398 // can't read it or other error; just skip it
399 } finally {
400 // close/delete the file
401 f.delete();
402 }
403 }
404 }
405 }
406 }
407
Christopher Tate91717492009-06-26 21:07:13 -0700408 // Add a transport to our set of available backends
409 private void registerTransport(String name, IBackupTransport transport) {
410 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700411 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700412 mTransports.put(name, transport);
413 }
414 }
415
Christopher Tate3799bc22009-05-06 16:13:56 -0700416 // ----- Track installation/removal of packages -----
417 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
418 public void onReceive(Context context, Intent intent) {
419 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
420
421 Uri uri = intent.getData();
422 if (uri == null) {
423 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700424 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700425 String pkgName = uri.getSchemeSpecificPart();
426 if (pkgName == null) {
427 return;
428 }
429
430 String action = intent.getAction();
431 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
432 synchronized (mBackupParticipants) {
433 Bundle extras = intent.getExtras();
434 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
435 // The package was just upgraded
436 updatePackageParticipantsLocked(pkgName);
437 } else {
438 // The package was just added
439 addPackageParticipantsLocked(pkgName);
440 }
441 }
442 }
443 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
444 Bundle extras = intent.getExtras();
445 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
446 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
447 } else {
448 synchronized (mBackupParticipants) {
449 removePackageParticipantsLocked(pkgName);
450 }
451 }
452 }
453 }
454 };
455
Dan Egnor87a02bc2009-06-17 02:30:10 -0700456 // ----- Track connection to GoogleBackupTransport service -----
457 ServiceConnection mGoogleConnection = new ServiceConnection() {
458 public void onServiceConnected(ComponentName name, IBinder service) {
459 if (DEBUG) Log.v(TAG, "Connected to Google transport");
460 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700461 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700462 }
463
464 public void onServiceDisconnected(ComponentName name) {
465 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
466 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700467 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700468 }
469 };
470
Joe Onorato8ad02812009-05-13 01:41:44 -0400471 // ----- Run the actual backup process asynchronously -----
472
Christopher Tate181fafa2009-05-14 11:12:14 -0700473 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400474 public void handleMessage(Message msg) {
475
476 switch (msg.what) {
477 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700478 {
Christopher Tate91717492009-06-26 21:07:13 -0700479 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700480 if (transport == null) {
481 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700482 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700483 break;
484 }
485
Joe Onorato8ad02812009-05-13 01:41:44 -0400486 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700487 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700488 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400489 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700490 // Do we have any work to do?
491 if (mPendingBackups.size() > 0) {
492 for (BackupRequest b: mPendingBackups.values()) {
493 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700494 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700495 Log.v(TAG, "clearing pending backups");
496 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700497
Christopher Tate49401dd2009-07-01 12:34:29 -0700498 // Start a new backup-queue journal file too
499 if (mJournalStream != null) {
500 try {
501 mJournalStream.close();
502 } catch (IOException e) {
503 // don't need to do anything
504 }
505 makeJournalLocked();
506 }
507
508 // At this point, we have started a new journal file, and the old
509 // file identity is being passed to the backup processing thread.
510 // When it completes successfully, that old journal file will be
511 // deleted. If we crash prior to that, the old journal is parsed
512 // at next boot and the journaled requests fulfilled.
513 (new PerformBackupThread(transport, queue, oldJournal)).start();
514 } else {
515 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700516 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700517 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400518 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700519 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700520 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700521
522 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400523 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700524
525 case MSG_RUN_RESTORE:
526 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700527 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400528 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700529 (new PerformRestoreThread(params.transport, params.observer,
530 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700531 break;
532 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700533
534 case MSG_RUN_CLEAR:
535 {
536 ClearParams params = (ClearParams)msg.obj;
537 (new PerformClearThread(params.transport, params.packageInfo)).start();
538 break;
539 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400540 }
541 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400542 }
543
Christopher Tate181fafa2009-05-14 11:12:14 -0700544 // Add the backup agents in the given package to our set of known backup participants.
545 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700546 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700547 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700548 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700549 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700550 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700551 }
552
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700554 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700555 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700556 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
557 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700558 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
559 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 }
561 }
562
Dan Egnorefe52642009-06-24 00:16:33 -0700563 for (PackageInfo pkg : targetPkgs) {
564 if (packageName == null || pkg.packageName.equals(packageName)) {
565 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700566 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700567 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700568 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700569 mBackupParticipants.put(uid, set);
570 }
Dan Egnorefe52642009-06-24 00:16:33 -0700571 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700572
573 // If we've never seen this app before, schedule a backup for it
574 if (!mEverStoredApps.contains(pkg.packageName)) {
575 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
576 + " never backed up; scheduling");
577 try {
578 dataChanged(pkg.packageName);
579 } catch (RemoteException e) {
580 // can't happen; it's a local method call
581 }
582 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700583 }
Christopher Tate487529a2009-04-29 14:03:25 -0700584 }
585 }
586
Christopher Tate6785dd82009-06-18 15:58:25 -0700587 // Remove the given package's entry from our known active set. If
588 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700589 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700590 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700591 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700592 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700593 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700594 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700595 int flags = PackageManager.GET_SIGNATURES;
596 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700597 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700598 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700599 }
600 } else {
601 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700602 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700603 }
604 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700605 }
606
Joe Onorato8ad02812009-05-13 01:41:44 -0400607 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700608 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700609 if (DEBUG) {
610 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
611 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700612 for (PackageInfo p : agents) {
613 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700614 }
615 }
Dan Egnorefe52642009-06-24 00:16:33 -0700616 for (PackageInfo pkg : agents) {
617 if (packageName == null || pkg.packageName.equals(packageName)) {
618 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700619 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700620 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700621 // Find the existing entry with the same package name, and remove it.
622 // We can't just remove(app) because the instances are different.
623 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700624 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700625 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700626 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700627 break;
628 }
629 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700630 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700631 mBackupParticipants.delete(uid);
632 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700633 }
634 }
635 }
636 }
637
Christopher Tate181fafa2009-05-14 11:12:14 -0700638 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700639 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700640 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700641 int flags = PackageManager.GET_SIGNATURES;
642 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
643 int N = packages.size();
644 for (int a = N-1; a >= 0; a--) {
645 ApplicationInfo app = packages.get(a).applicationInfo;
646 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
647 || app.backupAgentName == null) {
648 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700649 }
650 }
Dan Egnorefe52642009-06-24 00:16:33 -0700651 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700652 }
Christopher Tateaa088442009-06-16 18:25:46 -0700653
Christopher Tate3799bc22009-05-06 16:13:56 -0700654 // Reset the given package's known backup participants. Unlike add/remove, the update
655 // action cannot be passed a null package name.
656 void updatePackageParticipantsLocked(String packageName) {
657 if (packageName == null) {
658 Log.e(TAG, "updatePackageParticipants called with null package name");
659 return;
660 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700661 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700662
663 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700664 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700665 removePackageParticipantsLockedInner(packageName, allApps);
666 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700667 }
668
Christopher Tate73e02522009-07-15 14:18:26 -0700669 // Called from the backup thread: record that the given app has been successfully
670 // backed up at least once
671 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700672 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700673 synchronized (mEverStoredApps) {
674 if (mEverStoredApps.add(packageName)) {
675 try {
676 mEverStoredStream.writeUTF(packageName);
677 } catch (IOException e) {
678 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
679 try {
680 mEverStoredStream.close();
681 } catch (IOException ioe) {
682 // we're dropping it; no need to handle an exception on close here
683 }
684 mEverStoredStream = null;
685 }
686 }
687 }
688 }
689 }
690
Christopher Tatee97e8072009-07-15 16:45:50 -0700691 // Remove our awareness of having ever backed up the given package
692 void removeEverBackedUp(String packageName) {
693 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
694 + ", new set:");
695
696 if (mEverStoredStream != null) {
697 synchronized (mEverStoredApps) {
698 // Rewrite the file and rename to overwrite. If we reboot in the middle,
699 // we'll recognize on initialization time that the package no longer
700 // exists and fix it up then.
701 File tempKnownFile = new File(mBaseStateDir, "processed.new");
702 try {
703 mEverStoredStream.close();
704 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
705 mEverStoredApps.remove(packageName);
706 for (String s : mEverStoredApps) {
707 known.writeUTF(s);
708 if (DEBUG) Log.v(TAG, " " + s);
709 }
710 known.close();
711 tempKnownFile.renameTo(mEverStored);
712 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
713 } catch (IOException e) {
714 // Bad: we couldn't create the new copy. For safety's sake we
715 // abandon the whole process and remove all what's-backed-up
716 // state entirely, meaning we'll force a backup pass for every
717 // participant on the next boot or [re]install.
718 Log.w(TAG, "Error rewriting backed-up set; halting log");
719 mEverStoredStream = null;
720 mEverStoredApps.clear();
721 tempKnownFile.delete();
722 mEverStored.delete();
723 }
724 }
725 }
726 }
727
Dan Egnor87a02bc2009-06-17 02:30:10 -0700728 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700729 private IBackupTransport getTransport(String transportName) {
730 synchronized (mTransports) {
731 IBackupTransport transport = mTransports.get(transportName);
732 if (transport == null) {
733 Log.w(TAG, "Requested unavailable transport: " + transportName);
734 }
735 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700736 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700737 }
738
Christopher Tatedf01dea2009-06-09 20:45:02 -0700739 // fire off a backup agent, blocking until it attaches or times out
740 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
741 IBackupAgent agent = null;
742 synchronized(mAgentConnectLock) {
743 mConnecting = true;
744 mConnectedAgent = null;
745 try {
746 if (mActivityManager.bindBackupAgent(app, mode)) {
747 Log.d(TAG, "awaiting agent for " + app);
748
749 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700750 // only wait 10 seconds for the clear data to happen
751 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
752 while (mConnecting && mConnectedAgent == null
753 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700754 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700755 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700756 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700757 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700758 return null;
759 }
760 }
761
762 // if we timed out with no connect, abort and move on
763 if (mConnecting == true) {
764 Log.w(TAG, "Timeout waiting for agent " + app);
765 return null;
766 }
767 agent = mConnectedAgent;
768 }
769 } catch (RemoteException e) {
770 // can't happen
771 }
772 }
773 return agent;
774 }
775
Christopher Tatec7b31e32009-06-10 15:49:30 -0700776 // clear an application's data, blocking until the operation completes or times out
777 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700778 // Don't wipe packages marked allowClearUserData=false
779 try {
780 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
781 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
782 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
783 + packageName);
784 return;
785 }
786 } catch (NameNotFoundException e) {
787 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
788 return;
789 }
790
Christopher Tatec7b31e32009-06-10 15:49:30 -0700791 ClearDataObserver observer = new ClearDataObserver();
792
793 synchronized(mClearDataLock) {
794 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -0700795 try {
796 mActivityManager.clearApplicationUserData(packageName, observer);
797 } catch (RemoteException e) {
798 // can't happen because the activity manager is in this process
799 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700800
801 // only wait 10 seconds for the clear data to happen
802 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
803 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
804 try {
805 mClearDataLock.wait(5000);
806 } catch (InterruptedException e) {
807 // won't happen, but still.
808 mClearingData = false;
809 }
810 }
811 }
812 }
813
814 class ClearDataObserver extends IPackageDataObserver.Stub {
815 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -0700816 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700817 synchronized(mClearDataLock) {
818 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700819 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700820 }
821 }
822 }
823
Christopher Tate043dadc2009-06-02 16:11:00 -0700824 // ----- Back up a set of applications via a worker thread -----
825
826 class PerformBackupThread extends Thread {
827 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700828 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700829 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700830 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700831 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700832
Christopher Tateaa088442009-06-16 18:25:46 -0700833 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700834 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700835 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700836 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700837 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700838
839 try {
840 mStateDir = new File(mBaseStateDir, transport.transportDirName());
841 } catch (RemoteException e) {
842 // can't happen; the transport is local
843 }
844 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700845 }
846
847 @Override
848 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700849 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -0700850 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
851
Christopher Tate79588342009-06-30 16:11:49 -0700852 // Backups run at background priority
853 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
854
Christopher Tate043dadc2009-06-02 16:11:00 -0700855 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700856 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
857
858 // The package manager doesn't have a proper <application> etc, but since
859 // it's running here in the system process we can just set up its agent
860 // directly and use a synthetic BackupRequest. We always run this pass
861 // because it's cheap and this way we guarantee that we don't get out of
862 // step even if we're selecting among various transports at run time.
863 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
864 mPackageManager, allAgentPackages());
865 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
866 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
867 processOneBackup(pmRequest,
868 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
869
870 // Now run all the backups in our queue
871 int count = mQueue.size();
872 doQueuedBackups(mTransport);
873
874 // Finally, tear down the transport
875 if (mTransport.finishBackup()) {
876 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
877 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, count, millis);
878 } else {
879 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
880 Log.e(TAG, "Transport error in finishBackup()");
Dan Egnorefe52642009-06-24 00:16:33 -0700881 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700882
Dan Egnorbb9001c2009-07-27 12:20:13 -0700883 if (!mJournal.delete()) {
884 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
885 }
886 } catch (Exception e) {
887 Log.e(TAG, "Error in backup thread", e);
888 } finally {
889 // Only once we're entirely finished do we release the wakelock
890 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -0700891 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700892 }
893
894 private void doQueuedBackups(IBackupTransport transport) {
895 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700897
898 IBackupAgent agent = null;
899 int mode = (request.fullBackup)
900 ? IApplicationThread.BACKUP_MODE_FULL
901 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
902 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700903 agent = bindToAgentSynchronous(request.appInfo, mode);
904 if (agent != null) {
905 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700906 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700907
908 // unbind even on timeout, just in case
909 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700910 } catch (SecurityException ex) {
911 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700912 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700913 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700914 Log.v(TAG, "bind/backup threw");
915 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700916 }
917 }
918 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700919
920 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
921 final String packageName = request.appInfo.packageName;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700922 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700923
Dan Egnorbb9001c2009-07-27 12:20:13 -0700924 // !!! TODO: get the state file dir from the transport
925 File savedStateName = new File(mStateDir, packageName);
926 File backupDataName = new File(mDataDir, packageName + ".data");
927 File newStateName = new File(mStateDir, packageName + ".new");
928
929 ParcelFileDescriptor savedState = null;
930 ParcelFileDescriptor backupData = null;
931 ParcelFileDescriptor newState = null;
932
933 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700934 try {
935 // Look up the package info & signatures. This is first so that if it
936 // throws an exception, there's no file setup yet that would need to
937 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700938 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
939 // The metadata 'package' is synthetic
940 packInfo = new PackageInfo();
941 packInfo.packageName = packageName;
942 } else {
943 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700944 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700945 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700946
Christopher Tatec7b31e32009-06-10 15:49:30 -0700947 // In a full backup, we pass a null ParcelFileDescriptor as
948 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -0700949 if (!request.fullBackup) {
950 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700951 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -0700952 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
953 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700954
Dan Egnorbb9001c2009-07-27 12:20:13 -0700955 backupData = ParcelFileDescriptor.open(backupDataName,
956 ParcelFileDescriptor.MODE_READ_WRITE |
957 ParcelFileDescriptor.MODE_CREATE |
958 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700959
Dan Egnorbb9001c2009-07-27 12:20:13 -0700960 newState = ParcelFileDescriptor.open(newStateName,
961 ParcelFileDescriptor.MODE_READ_WRITE |
962 ParcelFileDescriptor.MODE_CREATE |
963 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700964
965 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -0700966 agent.doBackup(savedState, backupData, newState);
967 logBackupComplete(packageName);
968 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700969 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700970 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -0700971 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
972 backupDataName.delete();
973 newStateName.delete();
974 return;
975 } finally {
976 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
977 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
978 try { if (newState != null) newState.close(); } catch (IOException e) {}
979 savedState = backupData = newState = null;
980 }
981
982 // Now propagate the newly-backed-up data to the transport
983 try {
984 int size = (int) backupDataName.length();
985 if (size > 0) {
986 backupData = ParcelFileDescriptor.open(backupDataName,
987 ParcelFileDescriptor.MODE_READ_ONLY);
988
989 if (!transport.performBackup(packInfo, backupData)) throw new Exception();
990 } else {
991 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
992 }
993
994 // After successful transport, delete the now-stale data
995 // and juggle the files so that next time we supply the agent
996 // with the new state file it just created.
997 backupDataName.delete();
998 newStateName.renameTo(savedStateName);
999 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1000 } catch (Exception e) {
1001 Log.e(TAG, "Transport error backing up " + packageName, e);
1002 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1003 return;
1004 } finally {
1005 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001006 }
1007 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001008 }
1009
Christopher Tatedf01dea2009-06-09 20:45:02 -07001010
1011 // ----- Restore handling -----
1012
Christopher Tateabce4e82009-06-18 18:35:32 -07001013 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001014 // Allow unsigned apps, but not signed on one device and unsigned on the other
1015 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001016 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1017 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001018 if ((storedSigs == null || storedSigs.length == 0)
1019 && (deviceSigs == null || deviceSigs.length == 0)) {
1020 return true;
1021 }
1022 if (storedSigs == null || deviceSigs == null) {
1023 return false;
1024 }
1025
Christopher Tateabce4e82009-06-18 18:35:32 -07001026 // !!! TODO: this demands that every stored signature match one
1027 // that is present on device, and does not demand the converse.
1028 // Is this this right policy?
1029 int nStored = storedSigs.length;
1030 int nDevice = deviceSigs.length;
1031
1032 for (int i=0; i < nStored; i++) {
1033 boolean match = false;
1034 for (int j=0; j < nDevice; j++) {
1035 if (storedSigs[i].equals(deviceSigs[j])) {
1036 match = true;
1037 break;
1038 }
1039 }
1040 if (!match) {
1041 return false;
1042 }
1043 }
1044 return true;
1045 }
1046
Christopher Tatedf01dea2009-06-09 20:45:02 -07001047 class PerformRestoreThread extends Thread {
1048 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001049 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001050 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001051 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001052
Christopher Tate5cbbf562009-06-22 16:44:51 -07001053 class RestoreRequest {
1054 public PackageInfo app;
1055 public int storedAppVersion;
1056
1057 RestoreRequest(PackageInfo _app, int _version) {
1058 app = _app;
1059 storedAppVersion = _version;
1060 }
1061 }
1062
Christopher Tate7d562ec2009-06-25 18:03:43 -07001063 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001064 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001065 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001066 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001067 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001068 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001069
1070 try {
1071 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1072 } catch (RemoteException e) {
1073 // can't happen; the transport is local
1074 }
1075 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001076 }
1077
1078 @Override
1079 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001080 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001081 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
1082 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001083 /**
1084 * Restore sequence:
1085 *
Dan Egnorefe52642009-06-24 00:16:33 -07001086 * 1. get the restore set description for our identity
1087 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001088 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001089 * 3. for each app in the restore queue:
1090 * 3.a. clear the app data
1091 * 3.b. get the restore data for the app from the transport
1092 * 3.c. launch the backup agent for the app
1093 * 3.d. agent.doRestore() with the data from the server
1094 * 3.e. unbind the agent [and kill the app?]
1095 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001096 *
1097 * On errors, we try our best to recover and move on to the next
1098 * application, but if necessary we abort the whole operation --
1099 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001100 */
1101
Christopher Tate7d562ec2009-06-25 18:03:43 -07001102 int error = -1; // assume error
1103
Dan Egnorefe52642009-06-24 00:16:33 -07001104 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001105 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001106 // TODO: Log this before getAvailableRestoreSets, somehow
1107 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName());
Christopher Tateabce4e82009-06-18 18:35:32 -07001108
Dan Egnorefe52642009-06-24 00:16:33 -07001109 // Get the list of all packages which have backup enabled.
1110 // (Include the Package Manager metadata pseudo-package first.)
1111 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1112 PackageInfo omPackage = new PackageInfo();
1113 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1114 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001115
Dan Egnorefe52642009-06-24 00:16:33 -07001116 List<PackageInfo> agentPackages = allAgentPackages();
1117 restorePackages.addAll(agentPackages);
1118
Christopher Tate7d562ec2009-06-25 18:03:43 -07001119 // let the observer know that we're running
1120 if (mObserver != null) {
1121 try {
1122 // !!! TODO: get an actual count from the transport after
1123 // its startRestore() runs?
1124 mObserver.restoreStarting(restorePackages.size());
1125 } catch (RemoteException e) {
1126 Log.d(TAG, "Restore observer died at restoreStarting");
1127 mObserver = null;
1128 }
1129 }
1130
Dan Egnor156411d2009-06-26 13:20:02 -07001131 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -07001132 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001133 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001134 return;
1135 }
1136
1137 String packageName = mTransport.nextRestorePackage();
1138 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001139 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001140 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001141 return;
1142 } else if (packageName.equals("")) {
1143 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001144 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1145 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001146 return;
1147 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1148 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1149 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001150 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1151 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001152 return;
1153 }
1154
1155 // Pull the Package Manager metadata from the restore set first
1156 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1157 mPackageManager, agentPackages);
1158 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1159
Christopher Tate8c032472009-07-02 14:28:47 -07001160 // Verify that the backup set includes metadata. If not, we can't do
1161 // signature/version verification etc, so we simply do not proceed with
1162 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001163 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001164 Log.e(TAG, "No restore metadata available, so not restoring settings");
1165 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1166 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001167 return;
1168 }
1169
Christopher Tate7d562ec2009-06-25 18:03:43 -07001170 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001171 for (;;) {
1172 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001173
Dan Egnorefe52642009-06-24 00:16:33 -07001174 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001175 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001176 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001177 return;
1178 } else if (packageName.equals("")) {
1179 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001180 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001181
Christopher Tate7d562ec2009-06-25 18:03:43 -07001182 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001183 try {
1184 mObserver.onUpdate(count);
1185 } catch (RemoteException e) {
1186 Log.d(TAG, "Restore observer died in onUpdate");
1187 mObserver = null;
1188 }
1189 }
1190
Dan Egnorefe52642009-06-24 00:16:33 -07001191 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1192 if (metaInfo == null) {
1193 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001194 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1195 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001196 continue;
1197 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001198
Dan Egnorbb9001c2009-07-27 12:20:13 -07001199 PackageInfo packageInfo;
1200 try {
1201 int flags = PackageManager.GET_SIGNATURES;
1202 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1203 } catch (NameNotFoundException e) {
1204 Log.e(TAG, "Invalid package restoring data", e);
1205 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1206 "Package missing on device");
1207 continue;
1208 }
1209
Dan Egnorefe52642009-06-24 00:16:33 -07001210 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001211 String message = "Version " + metaInfo.versionCode
1212 + " > installed version " + packageInfo.versionCode;
1213 Log.w(TAG, "Package " + packageName + ": " + message);
1214 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001215 continue;
1216 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001217
Dan Egnorefe52642009-06-24 00:16:33 -07001218 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1219 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001220 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1221 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001222 continue;
1223 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001224
Dan Egnorefe52642009-06-24 00:16:33 -07001225 if (DEBUG) Log.v(TAG, "Package " + packageName
1226 + " restore version [" + metaInfo.versionCode
1227 + "] is compatible with installed version ["
1228 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001229
Dan Egnorefe52642009-06-24 00:16:33 -07001230 // Now perform the actual restore
1231 clearApplicationDataSynchronous(packageName);
1232 IBackupAgent agent = bindToAgentSynchronous(
1233 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001234 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001235 if (agent == null) {
1236 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001237 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1238 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001239 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001240 }
1241
Dan Egnorefe52642009-06-24 00:16:33 -07001242 try {
1243 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001244 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001245 } finally {
1246 // unbind even on timeout or failure, just in case
1247 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1248 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001249 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001250
1251 // if we get this far, report success to the observer
1252 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001253 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1254 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1255 } catch (Exception e) {
1256 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001257 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001258 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1259
Dan Egnorefe52642009-06-24 00:16:33 -07001260 try {
1261 mTransport.finishRestore();
1262 } catch (RemoteException e) {
1263 Log.e(TAG, "Error finishing restore", e);
1264 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001265
1266 if (mObserver != null) {
1267 try {
1268 mObserver.restoreFinished(error);
1269 } catch (RemoteException e) {
1270 Log.d(TAG, "Restore observer died at restoreFinished");
1271 }
1272 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001273
1274 // done; we can finally release the wakelock
1275 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001276 }
1277 }
1278
Dan Egnorefe52642009-06-24 00:16:33 -07001279 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1280 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001281 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001282 final String packageName = app.packageName;
1283
Dan Egnorbb9001c2009-07-27 12:20:13 -07001284 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001285
Christopher Tatec7b31e32009-06-10 15:49:30 -07001286 // !!! TODO: get the dirs from the transport
1287 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001288 File newStateName = new File(mStateDir, packageName + ".new");
1289 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001290
Dan Egnorbb9001c2009-07-27 12:20:13 -07001291 ParcelFileDescriptor backupData = null;
1292 ParcelFileDescriptor newState = null;
1293
1294 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001295 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001296 backupData = ParcelFileDescriptor.open(backupDataName,
1297 ParcelFileDescriptor.MODE_READ_WRITE |
1298 ParcelFileDescriptor.MODE_CREATE |
1299 ParcelFileDescriptor.MODE_TRUNCATE);
1300
1301 if (!mTransport.getRestoreData(backupData)) {
1302 Log.e(TAG, "Error getting restore data for " + packageName);
1303 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1304 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001305 }
1306
1307 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001309 backupData = ParcelFileDescriptor.open(backupDataName,
1310 ParcelFileDescriptor.MODE_READ_ONLY);
1311
Dan Egnorbb9001c2009-07-27 12:20:13 -07001312 newState = ParcelFileDescriptor.open(newStateName,
1313 ParcelFileDescriptor.MODE_READ_WRITE |
1314 ParcelFileDescriptor.MODE_CREATE |
1315 ParcelFileDescriptor.MODE_TRUNCATE);
1316
1317 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001318
1319 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001320 newStateName.renameTo(savedStateName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001321 int size = (int) backupDataName.length();
1322 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001323 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001324 Log.e(TAG, "Error restoring data for " + packageName, e);
1325 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1326
Christopher Tate96733042009-07-20 14:49:13 -07001327 // If the agent fails restore, it might have put the app's data
1328 // into an incoherent state. For consistency we wipe its data
1329 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001330 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001331 } finally {
1332 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001333 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1334 try { if (newState != null) newState.close(); } catch (IOException e) {}
1335 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001336 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001337 }
1338 }
1339
Christopher Tateee0e78a2009-07-02 11:17:03 -07001340 class PerformClearThread extends Thread {
1341 IBackupTransport mTransport;
1342 PackageInfo mPackage;
1343
1344 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1345 mTransport = transport;
1346 mPackage = packageInfo;
1347 }
1348
1349 @Override
1350 public void run() {
1351 try {
1352 // Clear the on-device backup state to ensure a full backup next time
1353 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1354 File stateFile = new File(stateDir, mPackage.packageName);
1355 stateFile.delete();
1356
1357 // Tell the transport to remove all the persistent storage for the app
1358 mTransport.clearBackupData(mPackage);
1359 } catch (RemoteException e) {
1360 // can't happen; the transport is local
1361 } finally {
1362 try {
1363 mTransport.finishBackup();
1364 } catch (RemoteException e) {
1365 // can't happen; the transport is local
1366 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001367
1368 // Last but not least, release the cpu
1369 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001370 }
1371 }
1372 }
1373
Christopher Tatedf01dea2009-06-09 20:45:02 -07001374
Christopher Tate487529a2009-04-29 14:03:25 -07001375 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001376
Christopher Tatea8bf8152009-04-30 11:36:21 -07001377 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001378 // Record that we need a backup pass for the caller. Since multiple callers
1379 // may share a uid, we need to note all candidates within that uid and schedule
1380 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001381 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001382
Christopher Tate63d27002009-06-16 17:16:42 -07001383 // If the caller does not hold the BACKUP permission, it can only request a
1384 // backup of its own data.
1385 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001386 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001387 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1388 targets = mBackupParticipants.get(Binder.getCallingUid());
1389 } else {
1390 // a caller with full permission can ask to back up any participating app
1391 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001392 targets = new HashSet<ApplicationInfo>();
1393 int N = mBackupParticipants.size();
1394 for (int i = 0; i < N; i++) {
1395 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1396 if (s != null) {
1397 targets.addAll(s);
1398 }
1399 }
1400 }
Christopher Tate487529a2009-04-29 14:03:25 -07001401 if (targets != null) {
1402 synchronized (mQueueLock) {
1403 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001404 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001405 // validate the caller-supplied package name against the known set of
1406 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001407 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001408 // Add the caller to the set of pending backups. If there is
1409 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001410 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001411 if (mPendingBackups.put(app, req) == null) {
1412 // Journal this request in case of crash. The put()
1413 // operation returned null when this package was not already
1414 // in the set; we want to avoid touching the disk redundantly.
1415 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001416
Christopher Tate22b60d82009-07-07 16:36:02 -07001417 if (DEBUG) {
1418 int numKeys = mPendingBackups.size();
1419 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1420 for (BackupRequest b : mPendingBackups.values()) {
1421 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1422 }
1423 }
1424 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001425 }
1426 }
Christopher Tate487529a2009-04-29 14:03:25 -07001427 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001428 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001429 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1430 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001431 }
1432 }
Christopher Tate46758122009-05-06 11:22:00 -07001433
Christopher Tatecde87f42009-06-12 12:55:53 -07001434 private void writeToJournalLocked(String str) {
1435 if (mJournalStream != null) {
1436 try {
1437 mJournalStream.writeUTF(str);
1438 } catch (IOException e) {
1439 Log.e(TAG, "Error writing to backup journal");
1440 mJournalStream = null;
1441 mJournal = null;
1442 }
1443 }
1444 }
1445
Christopher Tateee0e78a2009-07-02 11:17:03 -07001446 // Clear the given package's backup data from the current transport
1447 public void clearBackupData(String packageName) {
1448 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1449 PackageInfo info;
1450 try {
1451 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1452 } catch (NameNotFoundException e) {
1453 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1454 return;
1455 }
1456
1457 // If the caller does not hold the BACKUP permission, it can only request a
1458 // wipe of its own backed-up data.
1459 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001460 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001461 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1462 apps = mBackupParticipants.get(Binder.getCallingUid());
1463 } else {
1464 // a caller with full permission can ask to back up any participating app
1465 // !!! TODO: allow data-clear of ANY app?
1466 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1467 apps = new HashSet<ApplicationInfo>();
1468 int N = mBackupParticipants.size();
1469 for (int i = 0; i < N; i++) {
1470 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1471 if (s != null) {
1472 apps.addAll(s);
1473 }
1474 }
1475 }
1476
1477 // now find the given package in the set of candidate apps
1478 for (ApplicationInfo app : apps) {
1479 if (app.packageName.equals(packageName)) {
1480 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1481 // found it; fire off the clear request
1482 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001483 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001484 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001485 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1486 new ClearParams(getTransport(mCurrentTransport), info));
1487 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001488 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001489 }
1490 break;
1491 }
1492 }
1493 }
1494
Christopher Tateace7f092009-06-15 18:07:25 -07001495 // Run a backup pass immediately for any applications that have declared
1496 // that they have pending updates.
1497 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001499
Christopher Tateace7f092009-06-15 18:07:25 -07001500 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001501 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001502 try {
1503 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1504 mRunBackupIntent.send();
1505 } catch (PendingIntent.CanceledException e) {
1506 // should never happen
1507 Log.e(TAG, "run-backup intent cancelled!");
1508 }
Christopher Tate46758122009-05-06 11:22:00 -07001509 }
1510 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001511
Christopher Tate8031a3d2009-07-06 16:36:05 -07001512 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001513 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001514 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1515 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001516
1517 boolean wasEnabled = mEnabled;
1518 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001519 Settings.Secure.putInt(mContext.getContentResolver(),
1520 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001521 mEnabled = enable;
1522 }
1523
Christopher Tate49401dd2009-07-01 12:34:29 -07001524 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001525 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001526 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001527 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001528 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001529 // No longer enabled, so stop running backups
1530 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001531 }
1532 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001533 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001534
Christopher Tate8031a3d2009-07-06 16:36:05 -07001535 // Mark the backup service as having been provisioned
1536 public void setBackupProvisioned(boolean available) {
1537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1538 "setBackupProvisioned");
1539
1540 boolean wasProvisioned = mProvisioned;
1541 synchronized (this) {
1542 Settings.Secure.putInt(mContext.getContentResolver(),
1543 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1544 mProvisioned = available;
1545 }
1546
1547 synchronized (mQueueLock) {
1548 if (available && !wasProvisioned && mEnabled) {
1549 // we're now good to go, so start the backup alarms
1550 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1551 } else if (!available) {
1552 // No longer enabled, so stop running backups
1553 Log.w(TAG, "Backup service no longer provisioned");
1554 mAlarmManager.cancel(mRunBackupIntent);
1555 }
1556 }
1557 }
1558
1559 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1560 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1561 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1562 BACKUP_INTERVAL, mRunBackupIntent);
1563 }
1564
Christopher Tate6ef58a12009-06-29 14:56:28 -07001565 // Report whether the backup mechanism is currently enabled
1566 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001567 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001568 return mEnabled; // no need to synchronize just to read it
1569 }
1570
Christopher Tate91717492009-06-26 21:07:13 -07001571 // Report the name of the currently active transport
1572 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001573 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001574 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001575 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001576 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001577 }
1578
Christopher Tate91717492009-06-26 21:07:13 -07001579 // Report all known, available backup transports
1580 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001581 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001582
Christopher Tate91717492009-06-26 21:07:13 -07001583 String[] list = null;
1584 ArrayList<String> known = new ArrayList<String>();
1585 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1586 if (entry.getValue() != null) {
1587 known.add(entry.getKey());
1588 }
1589 }
1590
1591 if (known.size() > 0) {
1592 list = new String[known.size()];
1593 known.toArray(list);
1594 }
1595 return list;
1596 }
1597
1598 // Select which transport to use for the next backup operation. If the given
1599 // name is not one of the available transports, no action is taken and the method
1600 // returns null.
1601 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001603
1604 synchronized (mTransports) {
1605 String prevTransport = null;
1606 if (mTransports.get(transport) != null) {
1607 prevTransport = mCurrentTransport;
1608 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001609 Settings.Secure.putString(mContext.getContentResolver(),
1610 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001611 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1612 + " returning " + prevTransport);
1613 } else {
1614 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1615 }
1616 return prevTransport;
1617 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001618 }
1619
1620 // Callback: a requested backup agent has been instantiated. This should only
1621 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001622 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001623 synchronized(mAgentConnectLock) {
1624 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1625 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1626 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1627 mConnectedAgent = agent;
1628 mConnecting = false;
1629 } else {
1630 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1631 + " claiming agent connected");
1632 }
1633 mAgentConnectLock.notifyAll();
1634 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001635 }
1636
1637 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1638 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001639 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001640 public void agentDisconnected(String packageName) {
1641 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001642 synchronized(mAgentConnectLock) {
1643 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1644 mConnectedAgent = null;
1645 mConnecting = false;
1646 } else {
1647 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1648 + " claiming agent disconnected");
1649 }
1650 mAgentConnectLock.notifyAll();
1651 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001652 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001653
Christopher Tate8c850b72009-06-07 19:33:20 -07001654 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001655 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001657
1658 synchronized(this) {
1659 if (mActiveRestoreSession != null) {
1660 Log.d(TAG, "Restore session requested but one already active");
1661 return null;
1662 }
Christopher Tate91717492009-06-26 21:07:13 -07001663 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001664 }
1665 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001666 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001667
Christopher Tate9b3905c2009-06-08 15:24:01 -07001668 // ----- Restore session -----
1669
1670 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001671 private static final String TAG = "RestoreSession";
1672
Christopher Tate9b3905c2009-06-08 15:24:01 -07001673 private IBackupTransport mRestoreTransport = null;
1674 RestoreSet[] mRestoreSets = null;
1675
Christopher Tate91717492009-06-26 21:07:13 -07001676 RestoreSession(String transport) {
1677 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001678 }
1679
1680 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07001681 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04001682 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001683 "getAvailableRestoreSets");
1684
Christopher Tatef68eb502009-06-16 11:02:01 -07001685 try {
Christopher Tate43383042009-07-13 15:17:13 -07001686 if (mRestoreTransport == null) {
1687 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07001688 return null;
1689 }
1690 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001691 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001692 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001693 }
1694 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07001695 } catch (Exception e) {
1696 Log.e(TAG, "Error in getAvailableRestoreSets", e);
1697 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001698 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001699 }
1700
Dan Egnor0084da52009-07-29 12:57:16 -07001701 public synchronized int performRestore(long token, IRestoreObserver observer) {
1702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1703 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001704
Dan Egnor0084da52009-07-29 12:57:16 -07001705 if (DEBUG) Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001706
Dan Egnor0084da52009-07-29 12:57:16 -07001707 if (mRestoreTransport == null || mRestoreSets == null) {
1708 Log.e(TAG, "Ignoring performRestore() with no restore set");
1709 return -1;
1710 }
1711
1712 for (int i = 0; i < mRestoreSets.length; i++) {
1713 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001714 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07001715 mWakelock.acquire();
1716 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1717 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
1718 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001719 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07001720 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001721 }
1722 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001723 return -1;
1724 }
1725
Dan Egnor0084da52009-07-29 12:57:16 -07001726 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04001727 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001728 "endRestoreSession");
1729
Dan Egnor0084da52009-07-29 12:57:16 -07001730 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001731
Dan Egnor0084da52009-07-29 12:57:16 -07001732 synchronized (this) {
1733 try {
1734 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
1735 } catch (Exception e) {
1736 Log.e(TAG, "Error in finishRestore", e);
1737 } finally {
1738 mRestoreTransport = null;
1739 }
1740 }
1741
1742 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07001743 if (BackupManagerService.this.mActiveRestoreSession == this) {
1744 BackupManagerService.this.mActiveRestoreSession = null;
1745 } else {
1746 Log.e(TAG, "ending non-current restore session");
1747 }
1748 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001749 }
1750 }
1751
Christopher Tate043dadc2009-06-02 16:11:00 -07001752
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001753 @Override
1754 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1755 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001756 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1757 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001758 pw.println("Available transports:");
1759 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001760 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1761 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001762 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001763 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001764 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001765 for (int i=0; i<N; i++) {
1766 int uid = mBackupParticipants.keyAt(i);
1767 pw.print(" uid: ");
1768 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001769 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1770 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001771 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001772 }
1773 }
Christopher Tate73e02522009-07-15 14:18:26 -07001774 pw.println("Ever backed up: " + mEverStoredApps.size());
1775 for (String pkg : mEverStoredApps) {
1776 pw.println(" " + pkg);
1777 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001778 pw.println("Pending: " + mPendingBackups.size());
1779 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001780 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001781 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001782 }
1783 }
Christopher Tate487529a2009-04-29 14:03:25 -07001784}