blob: 7977d1f33b15dafb682144410acf48878142c967 [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;
20import android.app.IActivityManager;
21import android.app.IApplicationThread;
22import android.app.IBackupAgent;
Christopher Tate3799bc22009-05-06 16:13:56 -070023import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070024import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070025import android.content.Context;
26import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070027import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070028import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070029import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070030import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070031import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070032import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070033import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070034import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070036import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070037import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070039import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.Handler;
41import android.os.IBinder;
42import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070043import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070044import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070045import android.os.RemoteException;
46import android.util.Log;
47import android.util.SparseArray;
48
49import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070050import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070051import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070052import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070053
Christopher Tate9bbc21a2009-06-10 20:23:25 -070054import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070055import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070056
Christopher Tate6785dd82009-06-18 15:58:25 -070057import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070058import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070059
Christopher Tatecde87f42009-06-12 12:55:53 -070060import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070061import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070062import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070063import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070064import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070065import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070066import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040067import java.util.ArrayList;
68import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.util.HashSet;
70import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070071import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070072
73class BackupManagerService extends IBackupManager.Stub {
74 private static final String TAG = "BackupManagerService";
75 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070076
Christopher Tate49401dd2009-07-01 12:34:29 -070077 // How often we perform a backup pass. Privileged external callers can
78 // trigger an immediate pass.
79 private static final long BACKUP_INTERVAL = 60 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070082 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070083 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070084 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070085
86 // Timeout interval for deciding that a bind or clear-data has taken too long
87 static final long TIMEOUT_INTERVAL = 10 * 1000;
88
Christopher Tate487529a2009-04-29 14:03:25 -070089 private Context mContext;
90 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070091 private IActivityManager mActivityManager;
92 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tate487529a2009-04-29 14:03:25 -070093 private final BackupHandler mBackupHandler = new BackupHandler();
94 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -070095 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -070096 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070097 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070098 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070099 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700100 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700101
Christopher Tate181fafa2009-05-14 11:12:14 -0700102 BackupRequest(ApplicationInfo app, boolean isFull) {
103 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700104 fullBackup = isFull;
105 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700106
107 public String toString() {
108 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
109 }
Christopher Tate46758122009-05-06 11:22:00 -0700110 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400111 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700112 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
113 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700114
115 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700116 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700117
118 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700119 private final Object mQueueLock = new Object();
120
Christopher Tate043dadc2009-06-02 16:11:00 -0700121 // The thread performing the sequence of queued backups binds to each app's agent
122 // in succession. Bind notifications are asynchronously delivered through the
123 // Activity Manager; use this lock object to signal when a requested binding has
124 // completed.
125 private final Object mAgentConnectLock = new Object();
126 private IBackupAgent mConnectedAgent;
127 private volatile boolean mConnecting;
128
Christopher Tatec7b31e32009-06-10 15:49:30 -0700129 // A similar synchronicity mechanism around clearing apps' data for restore
130 private final Object mClearDataLock = new Object();
131 private volatile boolean mClearingData;
132
Christopher Tate91717492009-06-26 21:07:13 -0700133 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700134 private final HashMap<String,IBackupTransport> mTransports
135 = new HashMap<String,IBackupTransport>();
136 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700137 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700138 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700139
Christopher Tate7d562ec2009-06-25 18:03:43 -0700140 private class RestoreParams {
141 public IBackupTransport transport;
142 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700143 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700144
Dan Egnor156411d2009-06-26 13:20:02 -0700145 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700146 transport = _transport;
147 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700148 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700149 }
150 }
151
Christopher Tateee0e78a2009-07-02 11:17:03 -0700152 private class ClearParams {
153 public IBackupTransport transport;
154 public PackageInfo packageInfo;
155
156 ClearParams(IBackupTransport _transport, PackageInfo _info) {
157 transport = _transport;
158 packageInfo = _info;
159 }
160 }
161
Christopher Tate5cb400b2009-06-25 16:03:14 -0700162 // Where we keep our journal files and other bookkeeping
163 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700164 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700165 private File mJournalDir;
166 private File mJournal;
167 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700168
Christopher Tate487529a2009-04-29 14:03:25 -0700169 public BackupManagerService(Context context) {
170 mContext = context;
171 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700172 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700173
Christopher Tate22b87872009-05-04 16:41:53 -0700174 // Set up our bookkeeping
Dianne Hackborncf098292009-07-01 19:55:20 -0700175 mEnabled = Settings.Secure.getInt(context.getContentResolver(),
176 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700177 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700178 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700179
Christopher Tatecde87f42009-06-12 12:55:53 -0700180 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700181 mJournalDir = new File(mBaseStateDir, "pending");
182 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700183 makeJournalLocked(); // okay because no other threads are running yet
184
Christopher Tateabce4e82009-06-18 18:35:32 -0700185 // Build our mapping of uid to backup client services. This implicitly
186 // schedules a backup pass on the Package Manager metadata the first
187 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700188 synchronized (mBackupParticipants) {
189 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700190 }
191
Dan Egnor87a02bc2009-06-17 02:30:10 -0700192 // Set up our transport options and initialize the default transport
193 // TODO: Have transports register themselves somehow?
194 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700195 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700196 ComponentName localName = new ComponentName(context, LocalTransport.class);
197 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700198
Christopher Tate91717492009-06-26 21:07:13 -0700199 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700200 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
201 Settings.Secure.BACKUP_TRANSPORT);
202 if ("".equals(mCurrentTransport)) {
203 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700204 }
Christopher Tate91717492009-06-26 21:07:13 -0700205 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
206
207 // Attach to the Google backup transport. When this comes up, it will set
208 // itself as the current transport because we explicitly reset mCurrentTransport
209 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700210 Intent intent = new Intent().setComponent(new ComponentName(
211 "com.google.android.backup",
212 "com.google.android.backup.BackupTransportService"));
213 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700214
Christopher Tatecde87f42009-06-12 12:55:53 -0700215 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700216 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700217 parseLeftoverJournals();
218
Christopher Tate3799bc22009-05-06 16:13:56 -0700219 // Register for broadcasts about package install, etc., so we can
220 // update the provider list.
221 IntentFilter filter = new IntentFilter();
222 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
223 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
224 filter.addDataScheme("package");
225 mContext.registerReceiver(mBroadcastReceiver, filter);
Christopher Tate49401dd2009-07-01 12:34:29 -0700226
227 // Schedule the first backup pass -- okay because no other threads are
228 // running yet
229 if (mEnabled) {
230 scheduleBackupPassLocked(BACKUP_INTERVAL);
231 }
232}
Christopher Tate3799bc22009-05-06 16:13:56 -0700233
Christopher Tatecde87f42009-06-12 12:55:53 -0700234 private void makeJournalLocked() {
235 try {
236 mJournal = File.createTempFile("journal", null, mJournalDir);
237 mJournalStream = new RandomAccessFile(mJournal, "rwd");
238 } catch (IOException e) {
239 Log.e(TAG, "Unable to write backup journals");
240 mJournal = null;
241 mJournalStream = null;
242 }
243 }
244
245 private void parseLeftoverJournals() {
246 if (mJournal != null) {
247 File[] allJournals = mJournalDir.listFiles();
248 for (File f : allJournals) {
249 if (f.compareTo(mJournal) != 0) {
250 // This isn't the current journal, so it must be a leftover. Read
251 // out the package names mentioned there and schedule them for
252 // backup.
253 try {
254 Log.i(TAG, "Found stale backup journal, scheduling:");
255 RandomAccessFile in = new RandomAccessFile(f, "r");
256 while (true) {
257 String packageName = in.readUTF();
258 Log.i(TAG, " + " + packageName);
259 dataChanged(packageName);
260 }
261 } catch (EOFException e) {
262 // no more data; we're done
263 } catch (Exception e) {
264 // can't read it or other error; just skip it
265 } finally {
266 // close/delete the file
267 f.delete();
268 }
269 }
270 }
271 }
272 }
273
Christopher Tate91717492009-06-26 21:07:13 -0700274 // Add a transport to our set of available backends
275 private void registerTransport(String name, IBackupTransport transport) {
276 synchronized (mTransports) {
277 mTransports.put(name, transport);
278 }
279 }
280
Christopher Tate3799bc22009-05-06 16:13:56 -0700281 // ----- Track installation/removal of packages -----
282 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
283 public void onReceive(Context context, Intent intent) {
284 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
285
286 Uri uri = intent.getData();
287 if (uri == null) {
288 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700289 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700290 String pkgName = uri.getSchemeSpecificPart();
291 if (pkgName == null) {
292 return;
293 }
294
295 String action = intent.getAction();
296 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
297 synchronized (mBackupParticipants) {
298 Bundle extras = intent.getExtras();
299 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
300 // The package was just upgraded
301 updatePackageParticipantsLocked(pkgName);
302 } else {
303 // The package was just added
304 addPackageParticipantsLocked(pkgName);
305 }
306 }
307 }
308 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
309 Bundle extras = intent.getExtras();
310 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
311 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
312 } else {
313 synchronized (mBackupParticipants) {
314 removePackageParticipantsLocked(pkgName);
315 }
316 }
317 }
318 }
319 };
320
Dan Egnor87a02bc2009-06-17 02:30:10 -0700321 // ----- Track connection to GoogleBackupTransport service -----
322 ServiceConnection mGoogleConnection = new ServiceConnection() {
323 public void onServiceConnected(ComponentName name, IBinder service) {
324 if (DEBUG) Log.v(TAG, "Connected to Google transport");
325 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700326 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700327 }
328
329 public void onServiceDisconnected(ComponentName name) {
330 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
331 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700332 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700333 }
334 };
335
Joe Onorato8ad02812009-05-13 01:41:44 -0400336 // ----- Run the actual backup process asynchronously -----
337
Christopher Tate181fafa2009-05-14 11:12:14 -0700338 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400339 public void handleMessage(Message msg) {
340
341 switch (msg.what) {
342 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700343 {
Christopher Tate91717492009-06-26 21:07:13 -0700344 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700345 if (transport == null) {
346 Log.v(TAG, "Backup requested but no transport available");
347 break;
348 }
349
Joe Onorato8ad02812009-05-13 01:41:44 -0400350 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700351 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700352 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400353 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700354 // Do we have any work to do?
355 if (mPendingBackups.size() > 0) {
356 for (BackupRequest b: mPendingBackups.values()) {
357 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700358 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700359 Log.v(TAG, "clearing pending backups");
360 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700361
Christopher Tate49401dd2009-07-01 12:34:29 -0700362 // Start a new backup-queue journal file too
363 if (mJournalStream != null) {
364 try {
365 mJournalStream.close();
366 } catch (IOException e) {
367 // don't need to do anything
368 }
369 makeJournalLocked();
370 }
371
372 // At this point, we have started a new journal file, and the old
373 // file identity is being passed to the backup processing thread.
374 // When it completes successfully, that old journal file will be
375 // deleted. If we crash prior to that, the old journal is parsed
376 // at next boot and the journaled requests fulfilled.
377 (new PerformBackupThread(transport, queue, oldJournal)).start();
378 } else {
379 Log.v(TAG, "Backup requested but nothing pending");
380 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400381 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700382
Christopher Tate49401dd2009-07-01 12:34:29 -0700383 // Schedule the next pass.
384 synchronized (mQueueLock) {
385 scheduleBackupPassLocked(BACKUP_INTERVAL);
386 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700387 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700388 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700389
390 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400391 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700392
393 case MSG_RUN_RESTORE:
394 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700395 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400396 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Dan Egnor156411d2009-06-26 13:20:02 -0700397 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700398 break;
399 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700400
401 case MSG_RUN_CLEAR:
402 {
403 ClearParams params = (ClearParams)msg.obj;
404 (new PerformClearThread(params.transport, params.packageInfo)).start();
405 break;
406 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400407 }
408 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400409 }
410
Christopher Tate181fafa2009-05-14 11:12:14 -0700411 // Add the backup agents in the given package to our set of known backup participants.
412 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700413 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700414 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700415 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700416 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700417 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700418 }
419
Christopher Tate181fafa2009-05-14 11:12:14 -0700420 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700421 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700422 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700423 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
424 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700425 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
426 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700427 }
428 }
429
Dan Egnorefe52642009-06-24 00:16:33 -0700430 for (PackageInfo pkg : targetPkgs) {
431 if (packageName == null || pkg.packageName.equals(packageName)) {
432 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700433 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700434 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700435 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700436 mBackupParticipants.put(uid, set);
437 }
Dan Egnorefe52642009-06-24 00:16:33 -0700438 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700439 }
Christopher Tate487529a2009-04-29 14:03:25 -0700440 }
441 }
442
Christopher Tate6785dd82009-06-18 15:58:25 -0700443 // Remove the given package's entry from our known active set. If
444 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700445 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700446 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700447 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700448 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700449 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700450 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700451 int flags = PackageManager.GET_SIGNATURES;
452 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700453 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700454 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700455 }
456 } else {
457 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700458 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700459 }
460 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700461 }
462
Joe Onorato8ad02812009-05-13 01:41:44 -0400463 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700464 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700465 if (DEBUG) {
466 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
467 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700468 for (PackageInfo p : agents) {
469 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700470 }
471 }
Dan Egnorefe52642009-06-24 00:16:33 -0700472 for (PackageInfo pkg : agents) {
473 if (packageName == null || pkg.packageName.equals(packageName)) {
474 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700475 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700476 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700477 // Find the existing entry with the same package name, and remove it.
478 // We can't just remove(app) because the instances are different.
479 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700480 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700481 set.remove(entry);
482 break;
483 }
484 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700485 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700486 mBackupParticipants.delete(uid);
487 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700488 }
489 }
490 }
491 }
492
Christopher Tate181fafa2009-05-14 11:12:14 -0700493 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700494 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700495 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700496 int flags = PackageManager.GET_SIGNATURES;
497 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
498 int N = packages.size();
499 for (int a = N-1; a >= 0; a--) {
500 ApplicationInfo app = packages.get(a).applicationInfo;
501 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
502 || app.backupAgentName == null) {
503 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700504 }
505 }
Dan Egnorefe52642009-06-24 00:16:33 -0700506 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700507 }
Christopher Tateaa088442009-06-16 18:25:46 -0700508
Christopher Tate3799bc22009-05-06 16:13:56 -0700509 // Reset the given package's known backup participants. Unlike add/remove, the update
510 // action cannot be passed a null package name.
511 void updatePackageParticipantsLocked(String packageName) {
512 if (packageName == null) {
513 Log.e(TAG, "updatePackageParticipants called with null package name");
514 return;
515 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700516 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700517
518 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700519 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700520 removePackageParticipantsLockedInner(packageName, allApps);
521 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700522 }
523
Christopher Tate6785dd82009-06-18 15:58:25 -0700524 // The queue lock should be held when scheduling a backup pass
525 private void scheduleBackupPassLocked(long timeFromNowMillis) {
Christopher Tate6ef58a12009-06-29 14:56:28 -0700526 // We only schedule backups when we're actually enabled
527 synchronized (this) {
528 if (mEnabled) {
529 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
530 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
531 } else if (DEBUG) {
532 Log.v(TAG, "Disabled, so not scheduling backup pass");
533 }
534 }
Christopher Tate6785dd82009-06-18 15:58:25 -0700535 }
536
Dan Egnor87a02bc2009-06-17 02:30:10 -0700537 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700538 private IBackupTransport getTransport(String transportName) {
539 synchronized (mTransports) {
540 IBackupTransport transport = mTransports.get(transportName);
541 if (transport == null) {
542 Log.w(TAG, "Requested unavailable transport: " + transportName);
543 }
544 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700545 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700546 }
547
Christopher Tatedf01dea2009-06-09 20:45:02 -0700548 // fire off a backup agent, blocking until it attaches or times out
549 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
550 IBackupAgent agent = null;
551 synchronized(mAgentConnectLock) {
552 mConnecting = true;
553 mConnectedAgent = null;
554 try {
555 if (mActivityManager.bindBackupAgent(app, mode)) {
556 Log.d(TAG, "awaiting agent for " + app);
557
558 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700559 // only wait 10 seconds for the clear data to happen
560 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
561 while (mConnecting && mConnectedAgent == null
562 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700563 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700564 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700565 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700566 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700567 return null;
568 }
569 }
570
571 // if we timed out with no connect, abort and move on
572 if (mConnecting == true) {
573 Log.w(TAG, "Timeout waiting for agent " + app);
574 return null;
575 }
576 agent = mConnectedAgent;
577 }
578 } catch (RemoteException e) {
579 // can't happen
580 }
581 }
582 return agent;
583 }
584
Christopher Tatec7b31e32009-06-10 15:49:30 -0700585 // clear an application's data, blocking until the operation completes or times out
586 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700587 // Don't wipe packages marked allowClearUserData=false
588 try {
589 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
590 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
591 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
592 + packageName);
593 return;
594 }
595 } catch (NameNotFoundException e) {
596 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
597 return;
598 }
599
Christopher Tatec7b31e32009-06-10 15:49:30 -0700600 ClearDataObserver observer = new ClearDataObserver();
601
602 synchronized(mClearDataLock) {
603 mClearingData = true;
604 mPackageManager.clearApplicationUserData(packageName, observer);
605
606 // only wait 10 seconds for the clear data to happen
607 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
608 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
609 try {
610 mClearDataLock.wait(5000);
611 } catch (InterruptedException e) {
612 // won't happen, but still.
613 mClearingData = false;
614 }
615 }
616 }
617 }
618
619 class ClearDataObserver extends IPackageDataObserver.Stub {
620 public void onRemoveCompleted(String packageName, boolean succeeded)
621 throws android.os.RemoteException {
622 synchronized(mClearDataLock) {
623 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700624 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700625 }
626 }
627 }
628
Christopher Tate043dadc2009-06-02 16:11:00 -0700629 // ----- Back up a set of applications via a worker thread -----
630
631 class PerformBackupThread extends Thread {
632 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700633 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700634 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700635 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700636 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700637
Christopher Tateaa088442009-06-16 18:25:46 -0700638 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700639 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700640 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700641 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700642 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700643
644 try {
645 mStateDir = new File(mBaseStateDir, transport.transportDirName());
646 } catch (RemoteException e) {
647 // can't happen; the transport is local
648 }
649 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700650 }
651
652 @Override
653 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700654 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
655
Christopher Tate79588342009-06-30 16:11:49 -0700656 // Backups run at background priority
657 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
658
Christopher Tate5cb400b2009-06-25 16:03:14 -0700659 // The package manager doesn't have a proper <application> etc, but since
660 // it's running here in the system process we can just set up its agent
661 // directly and use a synthetic BackupRequest. We always run this pass
662 // because it's cheap and this way we guarantee that we don't get out of
663 // step even if we're selecting among various transports at run time.
664 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
665 mPackageManager, allAgentPackages());
666 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
667 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
668 processOneBackup(pmRequest,
669 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
670 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700671
672 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700673 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700674
675 // Finally, tear down the transport
676 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700677 if (!mTransport.finishBackup()) {
678 // STOPSHIP TODO: handle errors
679 Log.e(TAG, "Backup failure in finishBackup()");
680 }
681 } catch (RemoteException e) {
682 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700683 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700684
685 if (!mJournal.delete()) {
686 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
687 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700688 }
689
690 private void doQueuedBackups(IBackupTransport transport) {
691 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700692 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700693
694 IBackupAgent agent = null;
695 int mode = (request.fullBackup)
696 ? IApplicationThread.BACKUP_MODE_FULL
697 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
698 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700699 agent = bindToAgentSynchronous(request.appInfo, mode);
700 if (agent != null) {
701 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700702 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700703
704 // unbind even on timeout, just in case
705 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700706 } catch (SecurityException ex) {
707 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700708 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700709 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700710 Log.v(TAG, "bind/backup threw");
711 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700712 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700713
Christopher Tate043dadc2009-06-02 16:11:00 -0700714 }
715 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700716
717 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
718 final String packageName = request.appInfo.packageName;
719 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
720
721 try {
722 // Look up the package info & signatures. This is first so that if it
723 // throws an exception, there's no file setup yet that would need to
724 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700725 PackageInfo packInfo;
726 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
727 // The metadata 'package' is synthetic
728 packInfo = new PackageInfo();
729 packInfo.packageName = packageName;
730 } else {
731 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700732 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700733 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700734
735 // !!! TODO: get the state file dir from the transport
736 File savedStateName = new File(mStateDir, packageName);
737 File backupDataName = new File(mDataDir, packageName + ".data");
738 File newStateName = new File(mStateDir, packageName + ".new");
739
740 // In a full backup, we pass a null ParcelFileDescriptor as
741 // the saved-state "file"
742 ParcelFileDescriptor savedState = (request.fullBackup) ? null
743 : ParcelFileDescriptor.open(savedStateName,
744 ParcelFileDescriptor.MODE_READ_ONLY |
745 ParcelFileDescriptor.MODE_CREATE);
746
747 backupDataName.delete();
748 ParcelFileDescriptor backupData =
749 ParcelFileDescriptor.open(backupDataName,
750 ParcelFileDescriptor.MODE_READ_WRITE |
751 ParcelFileDescriptor.MODE_CREATE);
752
753 newStateName.delete();
754 ParcelFileDescriptor newState =
755 ParcelFileDescriptor.open(newStateName,
756 ParcelFileDescriptor.MODE_READ_WRITE |
757 ParcelFileDescriptor.MODE_CREATE);
758
759 // Run the target's backup pass
760 boolean success = false;
761 try {
762 agent.doBackup(savedState, backupData, newState);
763 success = true;
764 } finally {
765 if (savedState != null) {
766 savedState.close();
767 }
768 backupData.close();
769 newState.close();
770 }
771
772 // Now propagate the newly-backed-up data to the transport
773 if (success) {
774 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
775 backupData =
776 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700777 if (!transport.performBackup(packInfo, backupData)) {
778 // STOPSHIP TODO: handle errors
779 Log.e(TAG, "Backup failure in performBackup()");
780 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700781
782 // !!! TODO: After successful transport, delete the now-stale data
783 // and juggle the files so that next time the new state is passed
784 //backupDataName.delete();
785 newStateName.renameTo(savedStateName);
786 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700787 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700788 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700789 }
790 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700791 }
792
Christopher Tatedf01dea2009-06-09 20:45:02 -0700793
794 // ----- Restore handling -----
795
Christopher Tateabce4e82009-06-18 18:35:32 -0700796 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700797 // Allow unsigned apps, but not signed on one device and unsigned on the other
798 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700799 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
800 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700801 if ((storedSigs == null || storedSigs.length == 0)
802 && (deviceSigs == null || deviceSigs.length == 0)) {
803 return true;
804 }
805 if (storedSigs == null || deviceSigs == null) {
806 return false;
807 }
808
Christopher Tateabce4e82009-06-18 18:35:32 -0700809 // !!! TODO: this demands that every stored signature match one
810 // that is present on device, and does not demand the converse.
811 // Is this this right policy?
812 int nStored = storedSigs.length;
813 int nDevice = deviceSigs.length;
814
815 for (int i=0; i < nStored; i++) {
816 boolean match = false;
817 for (int j=0; j < nDevice; j++) {
818 if (storedSigs[i].equals(deviceSigs[j])) {
819 match = true;
820 break;
821 }
822 }
823 if (!match) {
824 return false;
825 }
826 }
827 return true;
828 }
829
Christopher Tatedf01dea2009-06-09 20:45:02 -0700830 class PerformRestoreThread extends Thread {
831 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700832 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700833 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700834 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700835 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700836
Christopher Tate5cbbf562009-06-22 16:44:51 -0700837 class RestoreRequest {
838 public PackageInfo app;
839 public int storedAppVersion;
840
841 RestoreRequest(PackageInfo _app, int _version) {
842 app = _app;
843 storedAppVersion = _version;
844 }
845 }
846
Christopher Tate7d562ec2009-06-25 18:03:43 -0700847 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700848 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700849 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400850 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700851 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700852 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700853
854 try {
855 mStateDir = new File(mBaseStateDir, transport.transportDirName());
856 } catch (RemoteException e) {
857 // can't happen; the transport is local
858 }
859 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700860 }
861
862 @Override
863 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400864 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
865 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700866 /**
867 * Restore sequence:
868 *
Dan Egnorefe52642009-06-24 00:16:33 -0700869 * 1. get the restore set description for our identity
870 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700871 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700872 * 3. for each app in the restore queue:
873 * 3.a. clear the app data
874 * 3.b. get the restore data for the app from the transport
875 * 3.c. launch the backup agent for the app
876 * 3.d. agent.doRestore() with the data from the server
877 * 3.e. unbind the agent [and kill the app?]
878 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700879 */
880
Christopher Tate7d562ec2009-06-25 18:03:43 -0700881 int error = -1; // assume error
882
Dan Egnorefe52642009-06-24 00:16:33 -0700883 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700884 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700885 RestoreSet[] images = mTransport.getAvailableRestoreSets();
886 if (images == null) {
887 // STOPSHIP TODO: Handle the failure somehow?
888 Log.e(TAG, "Error getting restore sets");
889 return;
890 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700891
Dan Egnorefe52642009-06-24 00:16:33 -0700892 if (images.length == 0) {
893 Log.i(TAG, "No restore sets available");
894 return;
895 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896
Dan Egnorefe52642009-06-24 00:16:33 -0700897 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700898
Dan Egnorefe52642009-06-24 00:16:33 -0700899 // Get the list of all packages which have backup enabled.
900 // (Include the Package Manager metadata pseudo-package first.)
901 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
902 PackageInfo omPackage = new PackageInfo();
903 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
904 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700905
Dan Egnorefe52642009-06-24 00:16:33 -0700906 List<PackageInfo> agentPackages = allAgentPackages();
907 restorePackages.addAll(agentPackages);
908
Christopher Tate7d562ec2009-06-25 18:03:43 -0700909 // let the observer know that we're running
910 if (mObserver != null) {
911 try {
912 // !!! TODO: get an actual count from the transport after
913 // its startRestore() runs?
914 mObserver.restoreStarting(restorePackages.size());
915 } catch (RemoteException e) {
916 Log.d(TAG, "Restore observer died at restoreStarting");
917 mObserver = null;
918 }
919 }
920
Dan Egnor156411d2009-06-26 13:20:02 -0700921 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700922 // STOPSHIP TODO: Handle the failure somehow?
923 Log.e(TAG, "Error starting restore operation");
924 return;
925 }
926
927 String packageName = mTransport.nextRestorePackage();
928 if (packageName == null) {
929 // STOPSHIP TODO: Handle the failure somehow?
930 Log.e(TAG, "Error getting first restore package");
931 return;
932 } else if (packageName.equals("")) {
933 Log.i(TAG, "No restore data available");
934 return;
935 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
936 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
937 + "\", found only \"" + packageName + "\"");
938 return;
939 }
940
941 // Pull the Package Manager metadata from the restore set first
942 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
943 mPackageManager, agentPackages);
944 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
945
Christopher Tate8c032472009-07-02 14:28:47 -0700946 // Verify that the backup set includes metadata. If not, we can't do
947 // signature/version verification etc, so we simply do not proceed with
948 // the restore operation.
949 Metadata pmMeta = pmAgent.getRestoredMetadata(packageName);
950 if (pmMeta == null) {
951 Log.i(TAG, "No restore metadata available, so not restoring settings");
952 return;
953 }
954
Christopher Tate7d562ec2009-06-25 18:03:43 -0700955 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700956 for (;;) {
957 packageName = mTransport.nextRestorePackage();
958 if (packageName == null) {
959 // STOPSHIP TODO: Handle the failure somehow?
960 Log.e(TAG, "Error getting next restore package");
961 return;
962 } else if (packageName.equals("")) {
963 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700964 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700965
Christopher Tate7d562ec2009-06-25 18:03:43 -0700966 if (mObserver != null) {
967 ++count;
968 try {
969 mObserver.onUpdate(count);
970 } catch (RemoteException e) {
971 Log.d(TAG, "Restore observer died in onUpdate");
972 mObserver = null;
973 }
974 }
975
Dan Egnorefe52642009-06-24 00:16:33 -0700976 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
977 if (metaInfo == null) {
978 Log.e(TAG, "Missing metadata for " + packageName);
979 continue;
980 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700981
Dan Egnorefe52642009-06-24 00:16:33 -0700982 int flags = PackageManager.GET_SIGNATURES;
983 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
984 if (metaInfo.versionCode > packageInfo.versionCode) {
985 Log.w(TAG, "Package " + packageName
986 + " restore version [" + metaInfo.versionCode
987 + "] is too new for installed version ["
988 + packageInfo.versionCode + "]");
989 continue;
990 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700991
Dan Egnorefe52642009-06-24 00:16:33 -0700992 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
993 Log.w(TAG, "Signature mismatch restoring " + packageName);
994 continue;
995 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700996
Dan Egnorefe52642009-06-24 00:16:33 -0700997 if (DEBUG) Log.v(TAG, "Package " + packageName
998 + " restore version [" + metaInfo.versionCode
999 + "] is compatible with installed version ["
1000 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001001
Dan Egnorefe52642009-06-24 00:16:33 -07001002 // Now perform the actual restore
1003 clearApplicationDataSynchronous(packageName);
1004 IBackupAgent agent = bindToAgentSynchronous(
1005 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001006 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001007 if (agent == null) {
1008 Log.w(TAG, "Can't find backup agent for " + packageName);
1009 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001010 }
1011
Dan Egnorefe52642009-06-24 00:16:33 -07001012 try {
1013 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1014 } finally {
1015 // unbind even on timeout or failure, just in case
1016 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1017 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001018 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001019
1020 // if we get this far, report success to the observer
1021 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001022 } catch (NameNotFoundException e) {
1023 // STOPSHIP TODO: Handle the failure somehow?
1024 Log.e(TAG, "Invalid paackage restoring data", e);
1025 } catch (RemoteException e) {
1026 // STOPSHIP TODO: Handle the failure somehow?
1027 Log.e(TAG, "Error restoring data", e);
1028 } finally {
1029 try {
1030 mTransport.finishRestore();
1031 } catch (RemoteException e) {
1032 Log.e(TAG, "Error finishing restore", e);
1033 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001034
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001035 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1036
Christopher Tate7d562ec2009-06-25 18:03:43 -07001037 if (mObserver != null) {
1038 try {
1039 mObserver.restoreFinished(error);
1040 } catch (RemoteException e) {
1041 Log.d(TAG, "Restore observer died at restoreFinished");
1042 }
1043 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001044 }
1045 }
1046
Dan Egnorefe52642009-06-24 00:16:33 -07001047 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1048 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001049 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001050 final String packageName = app.packageName;
1051
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001052 Log.d(TAG, "processOneRestore packageName=" + packageName);
1053
Christopher Tatec7b31e32009-06-10 15:49:30 -07001054 // !!! TODO: get the dirs from the transport
1055 File backupDataName = new File(mDataDir, packageName + ".restore");
1056 backupDataName.delete();
1057 try {
1058 ParcelFileDescriptor backupData =
1059 ParcelFileDescriptor.open(backupDataName,
1060 ParcelFileDescriptor.MODE_READ_WRITE |
1061 ParcelFileDescriptor.MODE_CREATE);
1062
1063 // Run the transport's restore pass
1064 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001065 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001066 if (!mTransport.getRestoreData(backupData)) {
1067 // STOPSHIP TODO: Handle this error somehow?
1068 Log.e(TAG, "Error getting restore data for " + packageName);
1069 return;
1070 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001071 } finally {
1072 backupData.close();
1073 }
1074
1075 // Okay, we have the data. Now have the agent do the restore.
1076 File newStateName = new File(mStateDir, packageName + ".new");
1077 ParcelFileDescriptor newState =
1078 ParcelFileDescriptor.open(newStateName,
1079 ParcelFileDescriptor.MODE_READ_WRITE |
1080 ParcelFileDescriptor.MODE_CREATE);
1081
1082 backupData = ParcelFileDescriptor.open(backupDataName,
1083 ParcelFileDescriptor.MODE_READ_ONLY);
1084
Christopher Tatec7b31e32009-06-10 15:49:30 -07001085 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001086 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001087 } finally {
1088 newState.close();
1089 backupData.close();
1090 }
1091
1092 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001093 File savedStateName = new File(mStateDir, packageName);
1094 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001095 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001096 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001097 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001098 }
1099 }
1100
Christopher Tateee0e78a2009-07-02 11:17:03 -07001101 class PerformClearThread extends Thread {
1102 IBackupTransport mTransport;
1103 PackageInfo mPackage;
1104
1105 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1106 mTransport = transport;
1107 mPackage = packageInfo;
1108 }
1109
1110 @Override
1111 public void run() {
1112 try {
1113 // Clear the on-device backup state to ensure a full backup next time
1114 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1115 File stateFile = new File(stateDir, mPackage.packageName);
1116 stateFile.delete();
1117
1118 // Tell the transport to remove all the persistent storage for the app
1119 mTransport.clearBackupData(mPackage);
1120 } catch (RemoteException e) {
1121 // can't happen; the transport is local
1122 } finally {
1123 try {
1124 mTransport.finishBackup();
1125 } catch (RemoteException e) {
1126 // can't happen; the transport is local
1127 }
1128 }
1129 }
1130 }
1131
Christopher Tatedf01dea2009-06-09 20:45:02 -07001132
Christopher Tate487529a2009-04-29 14:03:25 -07001133 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001134
Christopher Tatea8bf8152009-04-30 11:36:21 -07001135 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001136 // Record that we need a backup pass for the caller. Since multiple callers
1137 // may share a uid, we need to note all candidates within that uid and schedule
1138 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001139
1140 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001141
1142 // If the caller does not hold the BACKUP permission, it can only request a
1143 // backup of its own data.
1144 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001145 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001146 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1147 targets = mBackupParticipants.get(Binder.getCallingUid());
1148 } else {
1149 // a caller with full permission can ask to back up any participating app
1150 // !!! TODO: allow backup of ANY app?
1151 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1152 targets = new HashSet<ApplicationInfo>();
1153 int N = mBackupParticipants.size();
1154 for (int i = 0; i < N; i++) {
1155 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1156 if (s != null) {
1157 targets.addAll(s);
1158 }
1159 }
1160 }
Christopher Tate487529a2009-04-29 14:03:25 -07001161 if (targets != null) {
1162 synchronized (mQueueLock) {
1163 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001164 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001165 // validate the caller-supplied package name against the known set of
1166 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001167 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001168 // Add the caller to the set of pending backups. If there is
1169 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001170 BackupRequest req = new BackupRequest(app, false);
1171 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001172
1173 // Journal this request in case of crash
1174 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001175 }
1176 }
1177
Christopher Tate181fafa2009-05-14 11:12:14 -07001178 if (DEBUG) {
1179 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001180 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001181 for (BackupRequest b : mPendingBackups.values()) {
1182 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1183 }
1184 }
Christopher Tate487529a2009-04-29 14:03:25 -07001185 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001186 } else {
1187 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001188 }
1189 }
Christopher Tate46758122009-05-06 11:22:00 -07001190
Christopher Tatecde87f42009-06-12 12:55:53 -07001191 private void writeToJournalLocked(String str) {
1192 if (mJournalStream != null) {
1193 try {
1194 mJournalStream.writeUTF(str);
1195 } catch (IOException e) {
1196 Log.e(TAG, "Error writing to backup journal");
1197 mJournalStream = null;
1198 mJournal = null;
1199 }
1200 }
1201 }
1202
Christopher Tateee0e78a2009-07-02 11:17:03 -07001203 // Clear the given package's backup data from the current transport
1204 public void clearBackupData(String packageName) {
1205 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1206 PackageInfo info;
1207 try {
1208 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1209 } catch (NameNotFoundException e) {
1210 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1211 return;
1212 }
1213
1214 // If the caller does not hold the BACKUP permission, it can only request a
1215 // wipe of its own backed-up data.
1216 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001217 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001218 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1219 apps = mBackupParticipants.get(Binder.getCallingUid());
1220 } else {
1221 // a caller with full permission can ask to back up any participating app
1222 // !!! TODO: allow data-clear of ANY app?
1223 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1224 apps = new HashSet<ApplicationInfo>();
1225 int N = mBackupParticipants.size();
1226 for (int i = 0; i < N; i++) {
1227 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1228 if (s != null) {
1229 apps.addAll(s);
1230 }
1231 }
1232 }
1233
1234 // now find the given package in the set of candidate apps
1235 for (ApplicationInfo app : apps) {
1236 if (app.packageName.equals(packageName)) {
1237 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1238 // found it; fire off the clear request
1239 synchronized (mQueueLock) {
1240 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1241 new ClearParams(getTransport(mCurrentTransport), info));
1242 mBackupHandler.sendMessage(msg);
1243 }
1244 break;
1245 }
1246 }
1247 }
1248
Christopher Tateace7f092009-06-15 18:07:25 -07001249 // Run a backup pass immediately for any applications that have declared
1250 // that they have pending updates.
1251 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001252 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001253
Christopher Tateace7f092009-06-15 18:07:25 -07001254 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001255 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001256 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001257 }
1258 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001259
Christopher Tate6ef58a12009-06-29 14:56:28 -07001260 // Enable/disable the backup transport
1261 public void setBackupEnabled(boolean enable) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001262 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001263
1264 boolean wasEnabled = mEnabled;
1265 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001266 Settings.Secure.putInt(mContext.getContentResolver(),
1267 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001268 mEnabled = enable;
1269 }
1270
Christopher Tate49401dd2009-07-01 12:34:29 -07001271 synchronized (mQueueLock) {
1272 if (enable && !wasEnabled) {
1273 // if we've just been enabled, start scheduling backup passes
1274 scheduleBackupPassLocked(BACKUP_INTERVAL);
1275 } else if (!enable) {
1276 // No longer enabled, so stop running backups.
1277 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001278 }
1279 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001280 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001281
1282 // Report whether the backup mechanism is currently enabled
1283 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001284 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001285 return mEnabled; // no need to synchronize just to read it
1286 }
1287
Christopher Tate91717492009-06-26 21:07:13 -07001288 // Report the name of the currently active transport
1289 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001290 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1291 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001292 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001293 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001294 }
1295
Christopher Tate91717492009-06-26 21:07:13 -07001296 // Report all known, available backup transports
1297 public String[] listAllTransports() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001298 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001299
Christopher Tate91717492009-06-26 21:07:13 -07001300 String[] list = null;
1301 ArrayList<String> known = new ArrayList<String>();
1302 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1303 if (entry.getValue() != null) {
1304 known.add(entry.getKey());
1305 }
1306 }
1307
1308 if (known.size() > 0) {
1309 list = new String[known.size()];
1310 known.toArray(list);
1311 }
1312 return list;
1313 }
1314
1315 // Select which transport to use for the next backup operation. If the given
1316 // name is not one of the available transports, no action is taken and the method
1317 // returns null.
1318 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001319 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001320
1321 synchronized (mTransports) {
1322 String prevTransport = null;
1323 if (mTransports.get(transport) != null) {
1324 prevTransport = mCurrentTransport;
1325 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001326 Settings.Secure.putString(mContext.getContentResolver(),
1327 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001328 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1329 + " returning " + prevTransport);
1330 } else {
1331 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1332 }
1333 return prevTransport;
1334 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001335 }
1336
1337 // Callback: a requested backup agent has been instantiated. This should only
1338 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001339 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001340 synchronized(mAgentConnectLock) {
1341 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1342 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1343 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1344 mConnectedAgent = agent;
1345 mConnecting = false;
1346 } else {
1347 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1348 + " claiming agent connected");
1349 }
1350 mAgentConnectLock.notifyAll();
1351 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001352 }
1353
1354 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1355 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001356 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001357 public void agentDisconnected(String packageName) {
1358 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001359 synchronized(mAgentConnectLock) {
1360 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1361 mConnectedAgent = null;
1362 mConnecting = false;
1363 } else {
1364 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1365 + " claiming agent disconnected");
1366 }
1367 mAgentConnectLock.notifyAll();
1368 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001369 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001370
Christopher Tate8c850b72009-06-07 19:33:20 -07001371 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001372 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001373 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001374
1375 synchronized(this) {
1376 if (mActiveRestoreSession != null) {
1377 Log.d(TAG, "Restore session requested but one already active");
1378 return null;
1379 }
Christopher Tate91717492009-06-26 21:07:13 -07001380 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001381 }
1382 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001383 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001384
Christopher Tate9b3905c2009-06-08 15:24:01 -07001385 // ----- Restore session -----
1386
1387 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001388 private static final String TAG = "RestoreSession";
1389
Christopher Tate9b3905c2009-06-08 15:24:01 -07001390 private IBackupTransport mRestoreTransport = null;
1391 RestoreSet[] mRestoreSets = null;
1392
Christopher Tate91717492009-06-26 21:07:13 -07001393 RestoreSession(String transport) {
1394 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001395 }
1396
1397 // --- Binder interface ---
1398 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001399 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001400 "getAvailableRestoreSets");
1401
Christopher Tatef68eb502009-06-16 11:02:01 -07001402 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001403 synchronized(this) {
1404 if (mRestoreSets == null) {
1405 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1406 }
1407 return mRestoreSets;
1408 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001409 } catch (RuntimeException e) {
1410 Log.d(TAG, "getAvailableRestoreSets exception");
1411 e.printStackTrace();
1412 throw e;
1413 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001414 }
1415
Dan Egnor156411d2009-06-26 13:20:02 -07001416 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001417 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001418 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001419
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001420 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1421
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001422 if (mRestoreSets != null) {
1423 for (int i = 0; i < mRestoreSets.length; i++) {
1424 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001425 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001426 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001427 mBackupHandler.sendMessage(msg);
1428 return 0;
1429 }
1430 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001431 } else {
1432 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001433 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001434 return -1;
1435 }
1436
1437 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001438 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001439 "endRestoreSession");
1440
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001441 Log.d(TAG, "endRestoreSession");
1442
Dan Egnorefe52642009-06-24 00:16:33 -07001443 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001444 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001445 synchronized(BackupManagerService.this) {
1446 if (BackupManagerService.this.mActiveRestoreSession == this) {
1447 BackupManagerService.this.mActiveRestoreSession = null;
1448 } else {
1449 Log.e(TAG, "ending non-current restore session");
1450 }
1451 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001452 }
1453 }
1454
Christopher Tate043dadc2009-06-02 16:11:00 -07001455
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001456 @Override
1457 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1458 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001459 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate49401dd2009-07-01 12:34:29 -07001460 boolean scheduled = mBackupHandler.hasMessages(MSG_RUN_BACKUP);
1461 if (scheduled != mEnabled) {
1462 if (mEnabled) {
1463 pw.println("ERROR: backups enabled but none scheduled!");
1464 } else {
1465 pw.println("ERROR: backups are scheduled but not enabled!");
1466 }
1467 }
Christopher Tate91717492009-06-26 21:07:13 -07001468 pw.println("Available transports:");
1469 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001470 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1471 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001472 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001473 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001474 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001475 for (int i=0; i<N; i++) {
1476 int uid = mBackupParticipants.keyAt(i);
1477 pw.print(" uid: ");
1478 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001479 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1480 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001481 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001482 }
1483 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001484 pw.println("Pending: " + mPendingBackups.size());
1485 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001486 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001487 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001488 }
1489 }
Christopher Tate487529a2009-04-29 14:03:25 -07001490}