blob: 231582104cc813a75560ec92713a4dbb6e85d2f9 [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 Tate3799bc22009-05-06 16:13:56 -070034import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070035import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070036import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070037import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.os.Handler;
39import android.os.IBinder;
40import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070042import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070043import android.os.RemoteException;
44import android.util.Log;
45import android.util.SparseArray;
46
47import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070048import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070049import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070050import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070051
Christopher Tate9bbc21a2009-06-10 20:23:25 -070052import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070053import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070054
Christopher Tatecde87f42009-06-12 12:55:53 -070055import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070056import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070057import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070058import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070059import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070060import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070061import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070062import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040063import java.util.ArrayList;
64import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070065import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070066import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070067import java.util.List;
68
69class BackupManagerService extends IBackupManager.Stub {
70 private static final String TAG = "BackupManagerService";
71 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070072
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070073 private static final long COLLECTION_INTERVAL = 1000;
74 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070075
76 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070077 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070078 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070079
80 // Timeout interval for deciding that a bind or clear-data has taken too long
81 static final long TIMEOUT_INTERVAL = 10 * 1000;
82
Christopher Tate487529a2009-04-29 14:03:25 -070083 private Context mContext;
84 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070085 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070086 private final BackupHandler mBackupHandler = new BackupHandler();
87 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070088 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
89 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070090 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070091 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070092 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070093 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -070094
Christopher Tate181fafa2009-05-14 11:12:14 -070095 BackupRequest(ApplicationInfo app, boolean isFull) {
96 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070097 fullBackup = isFull;
98 }
Christopher Tate181fafa2009-05-14 11:12:14 -070099
100 public String toString() {
101 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
102 }
Christopher Tate46758122009-05-06 11:22:00 -0700103 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400104 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700105 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
106 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400107 // Backups that we have started. These are separate to prevent starvation
108 // if an app keeps re-enqueuing itself.
109 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700110 private final Object mQueueLock = new Object();
111
Christopher Tate043dadc2009-06-02 16:11:00 -0700112 // The thread performing the sequence of queued backups binds to each app's agent
113 // in succession. Bind notifications are asynchronously delivered through the
114 // Activity Manager; use this lock object to signal when a requested binding has
115 // completed.
116 private final Object mAgentConnectLock = new Object();
117 private IBackupAgent mConnectedAgent;
118 private volatile boolean mConnecting;
119
Christopher Tatec7b31e32009-06-10 15:49:30 -0700120 // A similar synchronicity mechanism around clearing apps' data for restore
121 private final Object mClearDataLock = new Object();
122 private volatile boolean mClearingData;
123
Christopher Tateaa088442009-06-16 18:25:46 -0700124 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700125 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700126 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700127 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700128
Christopher Tate22b87872009-05-04 16:41:53 -0700129 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700130 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700131 private File mJournalDir;
132 private File mJournal;
133 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700134
Christopher Tate487529a2009-04-29 14:03:25 -0700135 public BackupManagerService(Context context) {
136 mContext = context;
137 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700138 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700139
Christopher Tate22b87872009-05-04 16:41:53 -0700140 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700141 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700142 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700143 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700144
Christopher Tatecde87f42009-06-12 12:55:53 -0700145 // Set up the backup-request journaling
146 mJournalDir = new File(mStateDir, "pending");
147 mJournalDir.mkdirs();
148 makeJournalLocked(); // okay because no other threads are running yet
149
Christopher Tate3799bc22009-05-06 16:13:56 -0700150 // Build our mapping of uid to backup client services
151 synchronized (mBackupParticipants) {
152 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700153 }
154
Dan Egnor87a02bc2009-06-17 02:30:10 -0700155 // Set up our transport options and initialize the default transport
156 // TODO: Have transports register themselves somehow?
157 // TODO: Don't create transports that we don't need to?
158 mTransportId = BackupManager.TRANSPORT_GOOGLE;
159 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
160 mGoogleTransport = null;
161
162 // Attach to the Google backup transport.
163 Intent intent = new Intent().setComponent(new ComponentName(
164 "com.google.android.backup",
165 "com.google.android.backup.BackupTransportService"));
166 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700167
Christopher Tatecde87f42009-06-12 12:55:53 -0700168 // Now that we know about valid backup participants, parse any
169 // leftover journal files and schedule a new backup pass
170 parseLeftoverJournals();
171
Christopher Tate3799bc22009-05-06 16:13:56 -0700172 // Register for broadcasts about package install, etc., so we can
173 // update the provider list.
174 IntentFilter filter = new IntentFilter();
175 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
176 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
177 filter.addDataScheme("package");
178 mContext.registerReceiver(mBroadcastReceiver, filter);
179 }
180
Christopher Tatecde87f42009-06-12 12:55:53 -0700181 private void makeJournalLocked() {
182 try {
183 mJournal = File.createTempFile("journal", null, mJournalDir);
184 mJournalStream = new RandomAccessFile(mJournal, "rwd");
185 } catch (IOException e) {
186 Log.e(TAG, "Unable to write backup journals");
187 mJournal = null;
188 mJournalStream = null;
189 }
190 }
191
192 private void parseLeftoverJournals() {
193 if (mJournal != null) {
194 File[] allJournals = mJournalDir.listFiles();
195 for (File f : allJournals) {
196 if (f.compareTo(mJournal) != 0) {
197 // This isn't the current journal, so it must be a leftover. Read
198 // out the package names mentioned there and schedule them for
199 // backup.
200 try {
201 Log.i(TAG, "Found stale backup journal, scheduling:");
202 RandomAccessFile in = new RandomAccessFile(f, "r");
203 while (true) {
204 String packageName = in.readUTF();
205 Log.i(TAG, " + " + packageName);
206 dataChanged(packageName);
207 }
208 } catch (EOFException e) {
209 // no more data; we're done
210 } catch (Exception e) {
211 // can't read it or other error; just skip it
212 } finally {
213 // close/delete the file
214 f.delete();
215 }
216 }
217 }
218 }
219 }
220
Christopher Tate3799bc22009-05-06 16:13:56 -0700221 // ----- Track installation/removal of packages -----
222 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
223 public void onReceive(Context context, Intent intent) {
224 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
225
226 Uri uri = intent.getData();
227 if (uri == null) {
228 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700229 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700230 String pkgName = uri.getSchemeSpecificPart();
231 if (pkgName == null) {
232 return;
233 }
234
235 String action = intent.getAction();
236 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
237 synchronized (mBackupParticipants) {
238 Bundle extras = intent.getExtras();
239 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
240 // The package was just upgraded
241 updatePackageParticipantsLocked(pkgName);
242 } else {
243 // The package was just added
244 addPackageParticipantsLocked(pkgName);
245 }
246 }
247 }
248 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
249 Bundle extras = intent.getExtras();
250 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
251 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
252 } else {
253 synchronized (mBackupParticipants) {
254 removePackageParticipantsLocked(pkgName);
255 }
256 }
257 }
258 }
259 };
260
Dan Egnor87a02bc2009-06-17 02:30:10 -0700261 // ----- Track connection to GoogleBackupTransport service -----
262 ServiceConnection mGoogleConnection = new ServiceConnection() {
263 public void onServiceConnected(ComponentName name, IBinder service) {
264 if (DEBUG) Log.v(TAG, "Connected to Google transport");
265 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
266 }
267
268 public void onServiceDisconnected(ComponentName name) {
269 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
270 mGoogleTransport = null;
271 }
272 };
273
Joe Onorato8ad02812009-05-13 01:41:44 -0400274 // ----- Run the actual backup process asynchronously -----
275
Christopher Tate181fafa2009-05-14 11:12:14 -0700276 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400277 public void handleMessage(Message msg) {
278
279 switch (msg.what) {
280 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700281 {
282 IBackupTransport transport = getTransport(mTransportId);
283 if (transport == null) {
284 Log.v(TAG, "Backup requested but no transport available");
285 break;
286 }
287
Joe Onorato8ad02812009-05-13 01:41:44 -0400288 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700289 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400290 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700291 if (mPendingBackups.size() == 0) {
292 Log.v(TAG, "Backup requested but nothing pending");
293 break;
294 }
295
Joe Onoratod2110db2009-05-19 13:41:21 -0700296 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700297 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700298 for (BackupRequest b: mPendingBackups.values()) {
299 mBackupQueue.add(b);
300 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700301 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400302 }
Christopher Tateace7f092009-06-15 18:07:25 -0700303
304 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700305 if (mJournalStream != null) {
306 try {
307 mJournalStream.close();
308 } catch (IOException e) {
309 // don't need to do anything
310 }
311 makeJournalLocked();
312 }
313
314 // At this point, we have started a new journal file, and the old
315 // file identity is being passed to the backup processing thread.
316 // When it completes successfully, that old journal file will be
317 // deleted. If we crash prior to that, the old journal is parsed
318 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400319 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700320
321 (new PerformBackupThread(transport, mBackupQueue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700322 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700323 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700324
325 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400326 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700327
328 case MSG_RUN_RESTORE:
329 {
330 int token = msg.arg1;
331 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700332 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700333 break;
334 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400335 }
336 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400337 }
338
Christopher Tate181fafa2009-05-14 11:12:14 -0700339 // Add the backup agents in the given package to our set of known backup participants.
340 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700341 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700342 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700343 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700344 List<ApplicationInfo> targetApps = allAgentApps();
345 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700346 }
347
Christopher Tate181fafa2009-05-14 11:12:14 -0700348 private void addPackageParticipantsLockedInner(String packageName,
349 List<ApplicationInfo> targetApps) {
350 if (DEBUG) {
351 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
352 for (ApplicationInfo a : targetApps) {
353 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
354 }
355 }
356
357 for (ApplicationInfo app : targetApps) {
358 if (packageName == null || app.packageName.equals(packageName)) {
359 int uid = app.uid;
360 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700361 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700362 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700363 mBackupParticipants.put(uid, set);
364 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700365 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700366 }
Christopher Tate487529a2009-04-29 14:03:25 -0700367 }
368 }
369
Christopher Tate3799bc22009-05-06 16:13:56 -0700370 // Remove the given package's backup services from our known active set. If
371 // 'packageName' is null, *all* backup services will be removed.
372 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700373 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700374 List<ApplicationInfo> allApps = null;
375 if (packageName != null) {
376 allApps = new ArrayList<ApplicationInfo>();
377 try {
378 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
379 allApps.add(app);
380 } catch (Exception e) {
381 // just skip it
382 }
383 } else {
384 // all apps with agents
385 allApps = allAgentApps();
386 }
387 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700388 }
389
Joe Onorato8ad02812009-05-13 01:41:44 -0400390 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700391 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700392 if (DEBUG) {
393 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
394 + ") removing " + agents.size() + " entries");
395 for (ApplicationInfo a : agents) {
396 Log.v(TAG, " - " + a);
397 }
398 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700399 for (ApplicationInfo app : agents) {
400 if (packageName == null || app.packageName.equals(packageName)) {
401 int uid = app.uid;
402 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700403 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700404 // Find the existing entry with the same package name, and remove it.
405 // We can't just remove(app) because the instances are different.
406 for (ApplicationInfo entry: set) {
407 if (entry.packageName.equals(app.packageName)) {
408 set.remove(entry);
409 break;
410 }
411 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700412 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700413 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700414 }
415 }
416 }
417 }
418
Christopher Tate181fafa2009-05-14 11:12:14 -0700419 // Returns the set of all applications that define an android:backupAgent attribute
420 private List<ApplicationInfo> allAgentApps() {
421 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
422 int N = allApps.size();
423 if (N > 0) {
424 for (int a = N-1; a >= 0; a--) {
425 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700426 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
427 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700428 allApps.remove(a);
429 }
430 }
431 }
432 return allApps;
433 }
Christopher Tateaa088442009-06-16 18:25:46 -0700434
Christopher Tate3799bc22009-05-06 16:13:56 -0700435 // Reset the given package's known backup participants. Unlike add/remove, the update
436 // action cannot be passed a null package name.
437 void updatePackageParticipantsLocked(String packageName) {
438 if (packageName == null) {
439 Log.e(TAG, "updatePackageParticipants called with null package name");
440 return;
441 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700442 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700443
444 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700445 List<ApplicationInfo> allApps = allAgentApps();
446 removePackageParticipantsLockedInner(packageName, allApps);
447 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700448 }
449
Dan Egnor87a02bc2009-06-17 02:30:10 -0700450 // Return the given transport
451 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700452 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700453 case BackupManager.TRANSPORT_LOCAL:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700454 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700455
456 case BackupManager.TRANSPORT_GOOGLE:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700457 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700458
459 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700460 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700461 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700462 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700463 }
464
Christopher Tatedf01dea2009-06-09 20:45:02 -0700465 // fire off a backup agent, blocking until it attaches or times out
466 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
467 IBackupAgent agent = null;
468 synchronized(mAgentConnectLock) {
469 mConnecting = true;
470 mConnectedAgent = null;
471 try {
472 if (mActivityManager.bindBackupAgent(app, mode)) {
473 Log.d(TAG, "awaiting agent for " + app);
474
475 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700476 // only wait 10 seconds for the clear data to happen
477 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
478 while (mConnecting && mConnectedAgent == null
479 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700480 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700481 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700482 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700483 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700484 return null;
485 }
486 }
487
488 // if we timed out with no connect, abort and move on
489 if (mConnecting == true) {
490 Log.w(TAG, "Timeout waiting for agent " + app);
491 return null;
492 }
493 agent = mConnectedAgent;
494 }
495 } catch (RemoteException e) {
496 // can't happen
497 }
498 }
499 return agent;
500 }
501
Christopher Tatec7b31e32009-06-10 15:49:30 -0700502 // clear an application's data, blocking until the operation completes or times out
503 void clearApplicationDataSynchronous(String packageName) {
504 ClearDataObserver observer = new ClearDataObserver();
505
506 synchronized(mClearDataLock) {
507 mClearingData = true;
508 mPackageManager.clearApplicationUserData(packageName, observer);
509
510 // only wait 10 seconds for the clear data to happen
511 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
512 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
513 try {
514 mClearDataLock.wait(5000);
515 } catch (InterruptedException e) {
516 // won't happen, but still.
517 mClearingData = false;
518 }
519 }
520 }
521 }
522
523 class ClearDataObserver extends IPackageDataObserver.Stub {
524 public void onRemoveCompleted(String packageName, boolean succeeded)
525 throws android.os.RemoteException {
526 synchronized(mClearDataLock) {
527 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700528 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700529 }
530 }
531 }
532
Christopher Tate043dadc2009-06-02 16:11:00 -0700533 // ----- Back up a set of applications via a worker thread -----
534
535 class PerformBackupThread extends Thread {
536 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700537 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700538 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700539 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700540
Christopher Tateaa088442009-06-16 18:25:46 -0700541 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700542 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700543 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700544 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700545 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700546 }
547
548 @Override
549 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700550 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
551
Christopher Tatedf01dea2009-06-09 20:45:02 -0700552 // start up the transport
553 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700554 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700555 } catch (Exception e) {
556 Log.e(TAG, "Error session transport");
557 e.printStackTrace();
558 return;
559 }
560
Christopher Tate043dadc2009-06-02 16:11:00 -0700561 // The transport is up and running; now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700562 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700563
564 // Finally, tear down the transport
565 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700566 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700567 } catch (Exception e) {
568 Log.e(TAG, "Error ending transport");
569 e.printStackTrace();
570 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700571
572 if (!mJournal.delete()) {
573 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
574 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700575 }
576
577 private void doQueuedBackups(IBackupTransport transport) {
578 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700579 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700580
581 IBackupAgent agent = null;
582 int mode = (request.fullBackup)
583 ? IApplicationThread.BACKUP_MODE_FULL
584 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
585 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700586 agent = bindToAgentSynchronous(request.appInfo, mode);
587 if (agent != null) {
588 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700589 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700590
591 // unbind even on timeout, just in case
592 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700593 } catch (SecurityException ex) {
594 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700595 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700596 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700597 Log.v(TAG, "bind/backup threw");
598 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700599 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700600
Christopher Tate043dadc2009-06-02 16:11:00 -0700601 }
602 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700603
604 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
605 final String packageName = request.appInfo.packageName;
606 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
607
608 try {
609 // Look up the package info & signatures. This is first so that if it
610 // throws an exception, there's no file setup yet that would need to
611 // be unraveled.
612 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
613 PackageManager.GET_SIGNATURES);
614
615 // !!! TODO: get the state file dir from the transport
616 File savedStateName = new File(mStateDir, packageName);
617 File backupDataName = new File(mDataDir, packageName + ".data");
618 File newStateName = new File(mStateDir, packageName + ".new");
619
620 // In a full backup, we pass a null ParcelFileDescriptor as
621 // the saved-state "file"
622 ParcelFileDescriptor savedState = (request.fullBackup) ? null
623 : ParcelFileDescriptor.open(savedStateName,
624 ParcelFileDescriptor.MODE_READ_ONLY |
625 ParcelFileDescriptor.MODE_CREATE);
626
627 backupDataName.delete();
628 ParcelFileDescriptor backupData =
629 ParcelFileDescriptor.open(backupDataName,
630 ParcelFileDescriptor.MODE_READ_WRITE |
631 ParcelFileDescriptor.MODE_CREATE);
632
633 newStateName.delete();
634 ParcelFileDescriptor newState =
635 ParcelFileDescriptor.open(newStateName,
636 ParcelFileDescriptor.MODE_READ_WRITE |
637 ParcelFileDescriptor.MODE_CREATE);
638
639 // Run the target's backup pass
640 boolean success = false;
641 try {
642 agent.doBackup(savedState, backupData, newState);
643 success = true;
644 } finally {
645 if (savedState != null) {
646 savedState.close();
647 }
648 backupData.close();
649 newState.close();
650 }
651
652 // Now propagate the newly-backed-up data to the transport
653 if (success) {
654 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
655 backupData =
656 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
657 int error = transport.performBackup(packInfo, backupData);
658
659 // !!! TODO: After successful transport, delete the now-stale data
660 // and juggle the files so that next time the new state is passed
661 //backupDataName.delete();
662 newStateName.renameTo(savedStateName);
663 }
664 } catch (NameNotFoundException e) {
665 Log.e(TAG, "Package not found on backup: " + packageName);
666 } catch (FileNotFoundException fnf) {
667 Log.w(TAG, "File not found on backup: ");
668 fnf.printStackTrace();
669 } catch (RemoteException e) {
670 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
671 e.printStackTrace();
672 } catch (Exception e) {
673 Log.w(TAG, "Final exception guard in backup: ");
674 e.printStackTrace();
675 }
676 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700677 }
678
Christopher Tatedf01dea2009-06-09 20:45:02 -0700679
680 // ----- Restore handling -----
681
682 // Is the given package restorable on this device? Returns the on-device app's
683 // ApplicationInfo struct if it is; null if not.
684 //
685 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700686 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700687 if (packageInfo.packageName != null) {
688 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700689 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700690 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700691 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700692 return app;
693 }
694 } catch (Exception e) {
695 // doesn't exist on this device, or other error -- just ignore it.
696 }
697 }
698 return null;
699 }
700
701 class PerformRestoreThread extends Thread {
702 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700703 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700704 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700705
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700706 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700707 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700708 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700709 }
710
711 @Override
712 public void run() {
713 /**
714 * Restore sequence:
715 *
716 * 1. start up the transport session
717 * 2. get the restore set description for our identity
718 * 3. for each app in the restore set:
719 * 3.a. if it's restorable on this device, add it to the restore queue
720 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700721 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700722 * 4.b. get the restore data for the app from the transport
723 * 4.c. launch the backup agent for the app
724 * 4.d. agent.doRestore() with the data from the server
725 * 4.e. unbind the agent [and kill the app?]
726 * 5. shut down the transport
727 */
728
729 int err = -1;
730 try {
731 err = mTransport.startSession();
732 } catch (Exception e) {
733 Log.e(TAG, "Error starting transport for restore");
734 e.printStackTrace();
735 }
736
737 if (err == 0) {
738 // build the set of apps to restore
739 try {
740 RestoreSet[] images = mTransport.getAvailableRestoreSets();
741 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700742 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700743 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700744
745 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700746 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
747 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700748 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700749 // get the real PackageManager idea of the package
750 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700751 if (app != null) {
752 appsToRestore.add(app);
753 }
754 }
755
756 // now run the restore queue
757 doQueuedRestores(appsToRestore);
758 }
759 } catch (RemoteException e) {
760 // can't happen; transports run locally
761 }
762
763 // done; shut down the transport
764 try {
765 mTransport.endSession();
766 } catch (Exception e) {
767 Log.e(TAG, "Error ending transport for restore");
768 e.printStackTrace();
769 }
770 }
771
772 // even if the initial session startup failed, report that we're done here
773 }
774
775 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700776 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
777 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700778 Log.d(TAG, "starting agent for restore of " + app);
779
Christopher Tatedf01dea2009-06-09 20:45:02 -0700780 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700781 // Remove the app's data first
782 clearApplicationDataSynchronous(app.packageName);
783
784 // Now perform the restore into the clean app
785 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
786 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700787 if (agent != null) {
788 processOneRestore(app, agent);
789 }
790
791 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700792 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700793 } catch (SecurityException ex) {
794 // Try for the next one.
795 Log.d(TAG, "error in bind", ex);
796 } catch (RemoteException e) {
797 // can't happen
798 }
799
800 }
801 }
802
Christopher Tatec7b31e32009-06-10 15:49:30 -0700803 // Do the guts of a restore of one application, derived from the 'mImage'
804 // restore set via the 'mTransport' transport.
805 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700806 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700807 final String packageName = app.packageName;
808
809 // !!! TODO: get the dirs from the transport
810 File backupDataName = new File(mDataDir, packageName + ".restore");
811 backupDataName.delete();
812 try {
813 ParcelFileDescriptor backupData =
814 ParcelFileDescriptor.open(backupDataName,
815 ParcelFileDescriptor.MODE_READ_WRITE |
816 ParcelFileDescriptor.MODE_CREATE);
817
818 // Run the transport's restore pass
819 // Run the target's backup pass
820 int err = -1;
821 try {
822 err = mTransport.getRestoreData(mImage.token, app, backupData);
823 } catch (RemoteException e) {
824 // can't happen
825 } finally {
826 backupData.close();
827 }
828
829 // Okay, we have the data. Now have the agent do the restore.
830 File newStateName = new File(mStateDir, packageName + ".new");
831 ParcelFileDescriptor newState =
832 ParcelFileDescriptor.open(newStateName,
833 ParcelFileDescriptor.MODE_READ_WRITE |
834 ParcelFileDescriptor.MODE_CREATE);
835
836 backupData = ParcelFileDescriptor.open(backupDataName,
837 ParcelFileDescriptor.MODE_READ_ONLY);
838
839 boolean success = false;
840 try {
841 agent.doRestore(backupData, newState);
842 success = true;
843 } catch (Exception e) {
844 Log.e(TAG, "Restore failed for " + packageName);
845 e.printStackTrace();
846 } finally {
847 newState.close();
848 backupData.close();
849 }
850
851 // if everything went okay, remember the recorded state now
852 if (success) {
853 File savedStateName = new File(mStateDir, packageName);
854 newStateName.renameTo(savedStateName);
855 }
856 } catch (FileNotFoundException fnfe) {
857 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
858 } catch (IOException ioe) {
859 Log.e(TAG, "Unable to process restore file: " + ioe);
860 } catch (Exception e) {
861 Log.e(TAG, "Final exception guard in restore:");
862 e.printStackTrace();
863 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700864 }
865 }
866
867
Christopher Tate487529a2009-04-29 14:03:25 -0700868 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700869
Christopher Tatea8bf8152009-04-30 11:36:21 -0700870 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700871 // Record that we need a backup pass for the caller. Since multiple callers
872 // may share a uid, we need to note all candidates within that uid and schedule
873 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700874
875 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700876
877 // If the caller does not hold the BACKUP permission, it can only request a
878 // backup of its own data.
879 HashSet<ApplicationInfo> targets;
880 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
881 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
882 targets = mBackupParticipants.get(Binder.getCallingUid());
883 } else {
884 // a caller with full permission can ask to back up any participating app
885 // !!! TODO: allow backup of ANY app?
886 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
887 targets = new HashSet<ApplicationInfo>();
888 int N = mBackupParticipants.size();
889 for (int i = 0; i < N; i++) {
890 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
891 if (s != null) {
892 targets.addAll(s);
893 }
894 }
895 }
Christopher Tate487529a2009-04-29 14:03:25 -0700896 if (targets != null) {
897 synchronized (mQueueLock) {
898 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700899 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700900 // validate the caller-supplied package name against the known set of
901 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700902 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400903 // Add the caller to the set of pending backups. If there is
904 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700905 BackupRequest req = new BackupRequest(app, false);
906 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -0700907
908 // Journal this request in case of crash
909 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700910 }
911 }
912
Christopher Tate181fafa2009-05-14 11:12:14 -0700913 if (DEBUG) {
914 int numKeys = mPendingBackups.size();
915 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
916 for (BackupRequest b : mPendingBackups.values()) {
917 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
918 }
919 }
Christopher Tate487529a2009-04-29 14:03:25 -0700920 // Schedule a backup pass in a few minutes. As backup-eligible data
921 // keeps changing, continue to defer the backup pass until things
922 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700923 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700924 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
925 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700926 } else {
927 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700928 }
929 }
Christopher Tate46758122009-05-06 11:22:00 -0700930
Christopher Tatecde87f42009-06-12 12:55:53 -0700931 private void writeToJournalLocked(String str) {
932 if (mJournalStream != null) {
933 try {
934 mJournalStream.writeUTF(str);
935 } catch (IOException e) {
936 Log.e(TAG, "Error writing to backup journal");
937 mJournalStream = null;
938 mJournal = null;
939 }
940 }
941 }
942
Christopher Tateace7f092009-06-15 18:07:25 -0700943 // Run a backup pass immediately for any applications that have declared
944 // that they have pending updates.
945 public void backupNow() throws RemoteException {
946 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -0700947
Christopher Tateace7f092009-06-15 18:07:25 -0700948 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -0700949 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700950 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
951 mBackupHandler.sendEmptyMessage(MSG_RUN_BACKUP);
Christopher Tate46758122009-05-06 11:22:00 -0700952 }
953 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700954
Christopher Tateace7f092009-06-15 18:07:25 -0700955 // Report the currently active transport
956 public int getCurrentTransport() {
957 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
958 return mTransportId;
959 }
960
Christopher Tate043dadc2009-06-02 16:11:00 -0700961 // Select which transport to use for the next backup operation
962 public int selectBackupTransport(int transportId) {
963 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
964
Dan Egnor87a02bc2009-06-17 02:30:10 -0700965 int prevTransport = mTransportId;
966 mTransportId = transportId;
Christopher Tate043dadc2009-06-02 16:11:00 -0700967 return prevTransport;
968 }
969
970 // Callback: a requested backup agent has been instantiated. This should only
971 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700972 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700973 synchronized(mAgentConnectLock) {
974 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
975 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
976 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
977 mConnectedAgent = agent;
978 mConnecting = false;
979 } else {
980 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
981 + " claiming agent connected");
982 }
983 mAgentConnectLock.notifyAll();
984 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700985 }
986
987 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
988 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700989 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700990 public void agentDisconnected(String packageName) {
991 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700992 synchronized(mAgentConnectLock) {
993 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
994 mConnectedAgent = null;
995 mConnecting = false;
996 } else {
997 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
998 + " claiming agent disconnected");
999 }
1000 mAgentConnectLock.notifyAll();
1001 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001002 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001003
Christopher Tate8c850b72009-06-07 19:33:20 -07001004 // Hand off a restore session
1005 public IRestoreSession beginRestoreSession(int transportID) {
1006 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001007
1008 synchronized(this) {
1009 if (mActiveRestoreSession != null) {
1010 Log.d(TAG, "Restore session requested but one already active");
1011 return null;
1012 }
1013 mActiveRestoreSession = new RestoreSession(transportID);
1014 }
1015 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001016 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001017
Christopher Tate9b3905c2009-06-08 15:24:01 -07001018 // ----- Restore session -----
1019
1020 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001021 private static final String TAG = "RestoreSession";
1022
Christopher Tate9b3905c2009-06-08 15:24:01 -07001023 private IBackupTransport mRestoreTransport = null;
1024 RestoreSet[] mRestoreSets = null;
1025
1026 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001027 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001028 }
1029
1030 // --- Binder interface ---
1031 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001032 mContext.enforceCallingPermission("android.permission.BACKUP",
1033 "getAvailableRestoreSets");
1034
Christopher Tatef68eb502009-06-16 11:02:01 -07001035 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001036 synchronized(this) {
1037 if (mRestoreSets == null) {
1038 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1039 }
1040 return mRestoreSets;
1041 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001042 } catch (RuntimeException e) {
1043 Log.d(TAG, "getAvailableRestoreSets exception");
1044 e.printStackTrace();
1045 throw e;
1046 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001047 }
1048
1049 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001050 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1051
1052 if (mRestoreSets != null) {
1053 for (int i = 0; i < mRestoreSets.length; i++) {
1054 if (token == mRestoreSets[i].token) {
1055 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1056 mRestoreTransport);
1057 msg.arg1 = token;
1058 mBackupHandler.sendMessage(msg);
1059 return 0;
1060 }
1061 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001062 } else {
1063 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001064 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001065 return -1;
1066 }
1067
1068 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001069 mContext.enforceCallingPermission("android.permission.BACKUP",
1070 "endRestoreSession");
1071
Christopher Tate9b3905c2009-06-08 15:24:01 -07001072 mRestoreTransport.endSession();
1073 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001074 synchronized(BackupManagerService.this) {
1075 if (BackupManagerService.this.mActiveRestoreSession == this) {
1076 BackupManagerService.this.mActiveRestoreSession = null;
1077 } else {
1078 Log.e(TAG, "ending non-current restore session");
1079 }
1080 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001081 }
1082 }
1083
Christopher Tate043dadc2009-06-02 16:11:00 -07001084
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001085 @Override
1086 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1087 synchronized (mQueueLock) {
1088 int N = mBackupParticipants.size();
1089 pw.println("Participants:");
1090 for (int i=0; i<N; i++) {
1091 int uid = mBackupParticipants.keyAt(i);
1092 pw.print(" uid: ");
1093 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001094 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1095 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001096 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001097 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001098 }
1099 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001100 pw.println("Pending:");
1101 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1102 while (br.hasNext()) {
1103 pw.print(" ");
1104 pw.println(br);
1105 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001106 }
1107 }
Christopher Tate487529a2009-04-29 14:03:25 -07001108}