blob: 2fa18bf98c5f0e75308cb19d26ec4b6051cfd5d6 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate0749dcd2009-08-13 15:13:03 -070034import android.content.pm.PermissionInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070035import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070036import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070037import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070039import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070041import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070042import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070043import android.os.Handler;
44import android.os.IBinder;
45import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070047import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070048import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070050import android.os.SystemClock;
51import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070052import android.util.Log;
53import android.util.SparseArray;
54
55import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070056import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070057import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070058import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070059
Christopher Tated55e18a2009-09-21 10:12:59 -070060import com.android.internal.backup.BackupConstants;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070061import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070063
Christopher Tate6785dd82009-06-18 15:58:25 -070064import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070065import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070066
Christopher Tatecde87f42009-06-12 12:55:53 -070067import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070068import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070069import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
82 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Christopher Tate8031a3d2009-07-06 16:36:05 -070088 // The amount of time between the initial provisioning of the device and
89 // the first backup pass.
90 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
91
Christopher Tateb6787f22009-07-02 17:40:45 -070092 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070093 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070094 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070095 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070096 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070097
Dan Egnorbb9001c2009-07-27 12:20:13 -070098 // Event tags -- see system/core/logcat/event-log-tags
99 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
100 private static final int BACKUP_START_EVENT = 2821;
101 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
102 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
103 private static final int BACKUP_PACKAGE_EVENT = 2824;
104 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700105 private static final int BACKUP_RESET_EVENT = 2826;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700106
107 private static final int RESTORE_START_EVENT = 2830;
108 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
109 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
110 private static final int RESTORE_PACKAGE_EVENT = 2833;
111 private static final int RESTORE_SUCCESS_EVENT = 2834;
112
Christopher Tatec7b31e32009-06-10 15:49:30 -0700113 // Timeout interval for deciding that a bind or clear-data has taken too long
114 static final long TIMEOUT_INTERVAL = 10 * 1000;
115
Christopher Tate487529a2009-04-29 14:03:25 -0700116 private Context mContext;
117 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700118 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700119 private PowerManager mPowerManager;
120 private AlarmManager mAlarmManager;
121
Christopher Tate73e02522009-07-15 14:18:26 -0700122 boolean mEnabled; // access to this is synchronized on 'this'
123 boolean mProvisioned;
124 PowerManager.WakeLock mWakelock;
125 final BackupHandler mBackupHandler = new BackupHandler();
126 PendingIntent mRunBackupIntent;
127 BroadcastReceiver mRunBackupReceiver;
128 IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700129 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700130 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700131 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700132 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700133 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700134 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700135 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700136
Christopher Tate181fafa2009-05-14 11:12:14 -0700137 BackupRequest(ApplicationInfo app, boolean isFull) {
138 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700139 fullBackup = isFull;
140 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700141
142 public String toString() {
143 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
144 }
Christopher Tate46758122009-05-06 11:22:00 -0700145 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400146 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700147 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700148 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700149
150 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700151 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700152
153 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700154 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700155
Christopher Tate043dadc2009-06-02 16:11:00 -0700156 // The thread performing the sequence of queued backups binds to each app's agent
157 // in succession. Bind notifications are asynchronously delivered through the
158 // Activity Manager; use this lock object to signal when a requested binding has
159 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700160 final Object mAgentConnectLock = new Object();
161 IBackupAgent mConnectedAgent;
162 volatile boolean mConnecting;
Christopher Tate043dadc2009-06-02 16:11:00 -0700163
Christopher Tatec7b31e32009-06-10 15:49:30 -0700164 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700165 final Object mClearDataLock = new Object();
166 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700167
Christopher Tate91717492009-06-26 21:07:13 -0700168 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700169 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700170 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700171 String mCurrentTransport;
172 IBackupTransport mLocalTransport, mGoogleTransport;
173 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700174
Christopher Tate73e02522009-07-15 14:18:26 -0700175 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700176 public IBackupTransport transport;
177 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700178 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700179
Dan Egnor156411d2009-06-26 13:20:02 -0700180 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181 transport = _transport;
182 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700183 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700184 }
185 }
186
Christopher Tate73e02522009-07-15 14:18:26 -0700187 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700188 public IBackupTransport transport;
189 public PackageInfo packageInfo;
190
191 ClearParams(IBackupTransport _transport, PackageInfo _info) {
192 transport = _transport;
193 packageInfo = _info;
194 }
195 }
196
Christopher Tate5cb400b2009-06-25 16:03:14 -0700197 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700198 File mBaseStateDir;
199 File mDataDir;
200 File mJournalDir;
201 File mJournal;
202 RandomAccessFile mJournalStream;
203
204 // Keep a log of all the apps we've ever backed up
205 private File mEverStored;
206 private RandomAccessFile mEverStoredStream;
207 HashSet<String> mEverStoredApps = new HashSet<String>();
208
Christopher Tateaa088442009-06-16 18:25:46 -0700209
Christopher Tate487529a2009-04-29 14:03:25 -0700210 public BackupManagerService(Context context) {
211 mContext = context;
212 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700213 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700214
Christopher Tateb6787f22009-07-02 17:40:45 -0700215 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
216 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
217
Christopher Tate22b87872009-05-04 16:41:53 -0700218 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700219 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700220 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700221 // !!! TODO: mProvisioned needs to default to 0, not 1.
222 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700223 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700224 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700225 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700226
Christopher Tateb6787f22009-07-02 17:40:45 -0700227 mRunBackupReceiver = new RunBackupReceiver();
228 mRunBackupFilter = new IntentFilter();
229 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
230 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
231
232 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
233 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
234 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
235 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
236 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
237
Christopher Tatecde87f42009-06-12 12:55:53 -0700238 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700239 mJournalDir = new File(mBaseStateDir, "pending");
240 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700241 makeJournalLocked(); // okay because no other threads are running yet
242
Christopher Tate73e02522009-07-15 14:18:26 -0700243 // Set up the various sorts of package tracking we do
244 initPackageTracking();
245
Christopher Tateabce4e82009-06-18 18:35:32 -0700246 // Build our mapping of uid to backup client services. This implicitly
247 // schedules a backup pass on the Package Manager metadata the first
248 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700249 synchronized (mBackupParticipants) {
250 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700251 }
252
Dan Egnor87a02bc2009-06-17 02:30:10 -0700253 // Set up our transport options and initialize the default transport
254 // TODO: Have transports register themselves somehow?
255 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700256 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700257 ComponentName localName = new ComponentName(context, LocalTransport.class);
258 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700259
Christopher Tate91717492009-06-26 21:07:13 -0700260 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700261 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
262 Settings.Secure.BACKUP_TRANSPORT);
263 if ("".equals(mCurrentTransport)) {
264 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700265 }
Christopher Tate91717492009-06-26 21:07:13 -0700266 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
267
268 // Attach to the Google backup transport. When this comes up, it will set
269 // itself as the current transport because we explicitly reset mCurrentTransport
270 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700271 Intent intent = new Intent().setComponent(new ComponentName(
272 "com.google.android.backup",
273 "com.google.android.backup.BackupTransportService"));
274 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700275
Christopher Tatecde87f42009-06-12 12:55:53 -0700276 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700277 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700278 parseLeftoverJournals();
279
Christopher Tateb6787f22009-07-02 17:40:45 -0700280 // Power management
281 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
282
283 // Start the backup passes going
284 setBackupEnabled(areEnabled);
285 }
286
287 private class RunBackupReceiver extends BroadcastReceiver {
288 public void onReceive(Context context, Intent intent) {
289 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
290 if (DEBUG) Log.v(TAG, "Running a backup pass");
291
292 synchronized (mQueueLock) {
293 // acquire a wakelock and pass it to the backup thread. it will
294 // be released once backup concludes.
295 mWakelock.acquire();
296
297 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
298 mBackupHandler.sendMessage(msg);
299 }
300 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700301 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700302 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700303
Christopher Tate73e02522009-07-15 14:18:26 -0700304 private void initPackageTracking() {
305 if (DEBUG) Log.v(TAG, "Initializing package tracking");
306
Christopher Tatee97e8072009-07-15 16:45:50 -0700307 // Keep a log of what apps we've ever backed up. Because we might have
308 // rebooted in the middle of an operation that was removing something from
309 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700310 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700311 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700312 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700313 // If there are previous contents, parse them out then start a new
314 // file to continue the recordkeeping.
315 if (mEverStored.exists()) {
316 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
317 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700318
Christopher Tatedfec20b2009-08-03 15:38:09 -0700319 // parse its existing contents
320 mEverStoredStream.seek(0);
321 temp.seek(0);
322 try {
323 while (true) {
324 PackageInfo info;
325 String pkg = mEverStoredStream.readUTF();
326 try {
327 info = mPackageManager.getPackageInfo(pkg, 0);
328 mEverStoredApps.add(pkg);
329 temp.writeUTF(pkg);
330 if (DEBUG) Log.v(TAG, " + " + pkg);
331 } catch (NameNotFoundException e) {
332 // nope, this package was uninstalled; don't include it
333 if (DEBUG) Log.v(TAG, " - " + pkg);
334 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700335 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700336 } catch (EOFException e) {
337 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700338 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700339
Christopher Tatedfec20b2009-08-03 15:38:09 -0700340 // Once we've rewritten the backup history log, atomically replace the
341 // old one with the new one then reopen the file for continuing use.
342 temp.close();
343 mEverStoredStream.close();
344 tempProcessedFile.renameTo(mEverStored);
345 }
346 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700347 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700348 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700349 } catch (IOException e) {
350 Log.e(TAG, "Unable to open known-stored file!");
351 mEverStoredStream = null;
352 }
353
Christopher Tatee97e8072009-07-15 16:45:50 -0700354 // If we were in the middle of removing something from the ever-backed-up
355 // file, there might be a transient "processed.new" file still present.
356 // We've reconstructed a coherent state at this point though, so we can
357 // safely discard that file now.
358 if (tempProcessedFile.exists()) {
359 tempProcessedFile.delete();
360 }
361
Christopher Tate73e02522009-07-15 14:18:26 -0700362 // Register for broadcasts about package install, etc., so we can
363 // update the provider list.
364 IntentFilter filter = new IntentFilter();
365 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
366 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
367 filter.addDataScheme("package");
368 mContext.registerReceiver(mBroadcastReceiver, filter);
369 }
370
Christopher Tatecde87f42009-06-12 12:55:53 -0700371 private void makeJournalLocked() {
372 try {
373 mJournal = File.createTempFile("journal", null, mJournalDir);
374 mJournalStream = new RandomAccessFile(mJournal, "rwd");
375 } catch (IOException e) {
376 Log.e(TAG, "Unable to write backup journals");
377 mJournal = null;
378 mJournalStream = null;
379 }
380 }
381
382 private void parseLeftoverJournals() {
383 if (mJournal != null) {
384 File[] allJournals = mJournalDir.listFiles();
385 for (File f : allJournals) {
386 if (f.compareTo(mJournal) != 0) {
387 // This isn't the current journal, so it must be a leftover. Read
388 // out the package names mentioned there and schedule them for
389 // backup.
390 try {
391 Log.i(TAG, "Found stale backup journal, scheduling:");
392 RandomAccessFile in = new RandomAccessFile(f, "r");
393 while (true) {
394 String packageName = in.readUTF();
395 Log.i(TAG, " + " + packageName);
396 dataChanged(packageName);
397 }
398 } catch (EOFException e) {
399 // no more data; we're done
400 } catch (Exception e) {
401 // can't read it or other error; just skip it
402 } finally {
403 // close/delete the file
404 f.delete();
405 }
406 }
407 }
408 }
409 }
410
Christopher Tated55e18a2009-09-21 10:12:59 -0700411 // Reset all of our bookkeeping, in response to having been told that
412 // the backend data has been wiped [due to idle expiry, for example],
413 // so we must re-upload all saved settings.
414 void resetBackupState(File stateFileDir) {
415 synchronized (mQueueLock) {
416 // Wipe the "what we've ever backed up" tracking
417 try {
418 // close the ever-stored journal...
419 if (mEverStoredStream != null) {
420 mEverStoredStream.close();
421 }
422 // ... so we can delete it and start over
423 mEverStored.delete();
424 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
425 } catch (IOException e) {
426 Log.e(TAG, "Unable to open known-stored file!");
427 mEverStoredStream = null;
428 }
429 mEverStoredApps.clear();
430
431 // Remove all the state files
432 for (File sf : stateFileDir.listFiles()) {
433 sf.delete();
434 }
435
436 // Enqueue a new backup of every participant
437 int N = mBackupParticipants.size();
438 for (int i=0; i<N; i++) {
439 int uid = mBackupParticipants.keyAt(i);
440 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
441 for (ApplicationInfo app: participants) {
442 try {
443 dataChanged(app.packageName);
444 } catch (RemoteException e) {
445 // can't happen; we're in the same process
446 }
447 }
448 }
449 }
450 }
451
Christopher Tate91717492009-06-26 21:07:13 -0700452 // Add a transport to our set of available backends
453 private void registerTransport(String name, IBackupTransport transport) {
454 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700455 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700456 mTransports.put(name, transport);
457 }
458 }
459
Christopher Tate3799bc22009-05-06 16:13:56 -0700460 // ----- Track installation/removal of packages -----
461 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
462 public void onReceive(Context context, Intent intent) {
463 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
464
465 Uri uri = intent.getData();
466 if (uri == null) {
467 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700468 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700469 String pkgName = uri.getSchemeSpecificPart();
470 if (pkgName == null) {
471 return;
472 }
473
474 String action = intent.getAction();
475 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
476 synchronized (mBackupParticipants) {
477 Bundle extras = intent.getExtras();
478 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
479 // The package was just upgraded
480 updatePackageParticipantsLocked(pkgName);
481 } else {
482 // The package was just added
483 addPackageParticipantsLocked(pkgName);
484 }
485 }
486 }
487 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
488 Bundle extras = intent.getExtras();
489 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
490 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
491 } else {
492 synchronized (mBackupParticipants) {
493 removePackageParticipantsLocked(pkgName);
494 }
495 }
496 }
497 }
498 };
499
Dan Egnor87a02bc2009-06-17 02:30:10 -0700500 // ----- Track connection to GoogleBackupTransport service -----
501 ServiceConnection mGoogleConnection = new ServiceConnection() {
502 public void onServiceConnected(ComponentName name, IBinder service) {
503 if (DEBUG) Log.v(TAG, "Connected to Google transport");
504 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700505 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700506 }
507
508 public void onServiceDisconnected(ComponentName name) {
509 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
510 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700511 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700512 }
513 };
514
Joe Onorato8ad02812009-05-13 01:41:44 -0400515 // ----- Run the actual backup process asynchronously -----
516
Christopher Tate181fafa2009-05-14 11:12:14 -0700517 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400518 public void handleMessage(Message msg) {
519
520 switch (msg.what) {
521 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700522 {
Christopher Tate91717492009-06-26 21:07:13 -0700523 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700524 if (transport == null) {
525 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700526 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700527 break;
528 }
529
Joe Onorato8ad02812009-05-13 01:41:44 -0400530 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700531 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700532 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400533 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700534 // Do we have any work to do?
535 if (mPendingBackups.size() > 0) {
536 for (BackupRequest b: mPendingBackups.values()) {
537 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700538 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700539 Log.v(TAG, "clearing pending backups");
540 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700541
Christopher Tate49401dd2009-07-01 12:34:29 -0700542 // Start a new backup-queue journal file too
543 if (mJournalStream != null) {
544 try {
545 mJournalStream.close();
546 } catch (IOException e) {
547 // don't need to do anything
548 }
549 makeJournalLocked();
550 }
551
552 // At this point, we have started a new journal file, and the old
553 // file identity is being passed to the backup processing thread.
554 // When it completes successfully, that old journal file will be
555 // deleted. If we crash prior to that, the old journal is parsed
556 // at next boot and the journaled requests fulfilled.
557 (new PerformBackupThread(transport, queue, oldJournal)).start();
558 } else {
559 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700560 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700561 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400562 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700563 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700564 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700565
566 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400567 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700568
569 case MSG_RUN_RESTORE:
570 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700571 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400572 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700573 (new PerformRestoreThread(params.transport, params.observer,
574 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700575 break;
576 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700577
578 case MSG_RUN_CLEAR:
579 {
580 ClearParams params = (ClearParams)msg.obj;
581 (new PerformClearThread(params.transport, params.packageInfo)).start();
582 break;
583 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400584 }
585 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400586 }
587
Christopher Tate181fafa2009-05-14 11:12:14 -0700588 // Add the backup agents in the given package to our set of known backup participants.
589 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700590 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700591 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700592 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700593 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700594 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700595 }
596
Christopher Tate181fafa2009-05-14 11:12:14 -0700597 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700598 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700599 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700600 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
601 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700602 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700603 + " uid=" + p.applicationInfo.uid
604 + " killAfterRestore="
605 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
606 + " restoreNeedsApplication="
607 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
608 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700609 }
610 }
611
Dan Egnorefe52642009-06-24 00:16:33 -0700612 for (PackageInfo pkg : targetPkgs) {
613 if (packageName == null || pkg.packageName.equals(packageName)) {
614 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700615 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700616 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700617 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700618 mBackupParticipants.put(uid, set);
619 }
Dan Egnorefe52642009-06-24 00:16:33 -0700620 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700621
622 // If we've never seen this app before, schedule a backup for it
623 if (!mEverStoredApps.contains(pkg.packageName)) {
624 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
625 + " never backed up; scheduling");
626 try {
627 dataChanged(pkg.packageName);
628 } catch (RemoteException e) {
629 // can't happen; it's a local method call
630 }
631 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700632 }
Christopher Tate487529a2009-04-29 14:03:25 -0700633 }
634 }
635
Christopher Tate6785dd82009-06-18 15:58:25 -0700636 // Remove the given package's entry from our known active set. If
637 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700638 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700639 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700640 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700641 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700642 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700643 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700644 int flags = PackageManager.GET_SIGNATURES;
645 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700646 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700647 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700648 }
649 } else {
650 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700651 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700652 }
653 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700654 }
655
Joe Onorato8ad02812009-05-13 01:41:44 -0400656 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700657 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700658 if (DEBUG) {
659 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
660 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700661 for (PackageInfo p : agents) {
662 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700663 }
664 }
Dan Egnorefe52642009-06-24 00:16:33 -0700665 for (PackageInfo pkg : agents) {
666 if (packageName == null || pkg.packageName.equals(packageName)) {
667 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700668 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700669 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700670 // Find the existing entry with the same package name, and remove it.
671 // We can't just remove(app) because the instances are different.
672 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700673 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700674 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700675 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700676 break;
677 }
678 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700679 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700680 mBackupParticipants.delete(uid);
681 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700682 }
683 }
684 }
685 }
686
Christopher Tate181fafa2009-05-14 11:12:14 -0700687 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700688 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700689 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700690 int flags = PackageManager.GET_SIGNATURES;
691 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
692 int N = packages.size();
693 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700694 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700695 try {
696 ApplicationInfo app = pkg.applicationInfo;
697 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
698 || app.backupAgentName == null
699 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
700 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
701 packages.remove(a);
702 }
703 else {
704 // we will need the shared library path, so look that up and store it here
705 app = mPackageManager.getApplicationInfo(pkg.packageName,
706 PackageManager.GET_SHARED_LIBRARY_FILES);
707 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
708 }
709 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700710 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700711 }
712 }
Dan Egnorefe52642009-06-24 00:16:33 -0700713 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700714 }
Christopher Tateaa088442009-06-16 18:25:46 -0700715
Christopher Tate3799bc22009-05-06 16:13:56 -0700716 // Reset the given package's known backup participants. Unlike add/remove, the update
717 // action cannot be passed a null package name.
718 void updatePackageParticipantsLocked(String packageName) {
719 if (packageName == null) {
720 Log.e(TAG, "updatePackageParticipants called with null package name");
721 return;
722 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700723 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700724
725 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700726 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700727 removePackageParticipantsLockedInner(packageName, allApps);
728 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700729 }
730
Christopher Tate73e02522009-07-15 14:18:26 -0700731 // Called from the backup thread: record that the given app has been successfully
732 // backed up at least once
733 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700734 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700735 synchronized (mEverStoredApps) {
736 if (mEverStoredApps.add(packageName)) {
737 try {
738 mEverStoredStream.writeUTF(packageName);
739 } catch (IOException e) {
740 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
741 try {
742 mEverStoredStream.close();
743 } catch (IOException ioe) {
744 // we're dropping it; no need to handle an exception on close here
745 }
746 mEverStoredStream = null;
747 }
748 }
749 }
750 }
751 }
752
Christopher Tatee97e8072009-07-15 16:45:50 -0700753 // Remove our awareness of having ever backed up the given package
754 void removeEverBackedUp(String packageName) {
755 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
756 + ", new set:");
757
758 if (mEverStoredStream != null) {
759 synchronized (mEverStoredApps) {
760 // Rewrite the file and rename to overwrite. If we reboot in the middle,
761 // we'll recognize on initialization time that the package no longer
762 // exists and fix it up then.
763 File tempKnownFile = new File(mBaseStateDir, "processed.new");
764 try {
765 mEverStoredStream.close();
766 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
767 mEverStoredApps.remove(packageName);
768 for (String s : mEverStoredApps) {
769 known.writeUTF(s);
770 if (DEBUG) Log.v(TAG, " " + s);
771 }
772 known.close();
773 tempKnownFile.renameTo(mEverStored);
774 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
775 } catch (IOException e) {
776 // Bad: we couldn't create the new copy. For safety's sake we
777 // abandon the whole process and remove all what's-backed-up
778 // state entirely, meaning we'll force a backup pass for every
779 // participant on the next boot or [re]install.
780 Log.w(TAG, "Error rewriting backed-up set; halting log");
781 mEverStoredStream = null;
782 mEverStoredApps.clear();
783 tempKnownFile.delete();
784 mEverStored.delete();
785 }
786 }
787 }
788 }
789
Dan Egnor87a02bc2009-06-17 02:30:10 -0700790 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700791 private IBackupTransport getTransport(String transportName) {
792 synchronized (mTransports) {
793 IBackupTransport transport = mTransports.get(transportName);
794 if (transport == null) {
795 Log.w(TAG, "Requested unavailable transport: " + transportName);
796 }
797 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700798 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700799 }
800
Christopher Tatedf01dea2009-06-09 20:45:02 -0700801 // fire off a backup agent, blocking until it attaches or times out
802 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
803 IBackupAgent agent = null;
804 synchronized(mAgentConnectLock) {
805 mConnecting = true;
806 mConnectedAgent = null;
807 try {
808 if (mActivityManager.bindBackupAgent(app, mode)) {
809 Log.d(TAG, "awaiting agent for " + app);
810
811 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700812 // only wait 10 seconds for the clear data to happen
813 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
814 while (mConnecting && mConnectedAgent == null
815 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700816 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700817 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700818 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700819 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700820 return null;
821 }
822 }
823
824 // if we timed out with no connect, abort and move on
825 if (mConnecting == true) {
826 Log.w(TAG, "Timeout waiting for agent " + app);
827 return null;
828 }
829 agent = mConnectedAgent;
830 }
831 } catch (RemoteException e) {
832 // can't happen
833 }
834 }
835 return agent;
836 }
837
Christopher Tatec7b31e32009-06-10 15:49:30 -0700838 // clear an application's data, blocking until the operation completes or times out
839 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700840 // Don't wipe packages marked allowClearUserData=false
841 try {
842 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
843 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
844 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
845 + packageName);
846 return;
847 }
848 } catch (NameNotFoundException e) {
849 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
850 return;
851 }
852
Christopher Tatec7b31e32009-06-10 15:49:30 -0700853 ClearDataObserver observer = new ClearDataObserver();
854
855 synchronized(mClearDataLock) {
856 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700857 /* This is causing some critical processes to be killed during setup.
858 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700859 try {
860 mActivityManager.clearApplicationUserData(packageName, observer);
861 } catch (RemoteException e) {
862 // can't happen because the activity manager is in this process
863 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700864 */
865 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700866
867 // only wait 10 seconds for the clear data to happen
868 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
869 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
870 try {
871 mClearDataLock.wait(5000);
872 } catch (InterruptedException e) {
873 // won't happen, but still.
874 mClearingData = false;
875 }
876 }
877 }
878 }
879
880 class ClearDataObserver extends IPackageDataObserver.Stub {
881 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -0700882 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700883 synchronized(mClearDataLock) {
884 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700885 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700886 }
887 }
888 }
889
Christopher Tate043dadc2009-06-02 16:11:00 -0700890 // ----- Back up a set of applications via a worker thread -----
891
892 class PerformBackupThread extends Thread {
893 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700894 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700895 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700896 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700897 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700898
Christopher Tateaa088442009-06-16 18:25:46 -0700899 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700900 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700901 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700902 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700903 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700904
905 try {
906 mStateDir = new File(mBaseStateDir, transport.transportDirName());
907 } catch (RemoteException e) {
908 // can't happen; the transport is local
909 }
910 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700911 }
912
913 @Override
914 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -0700915 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700916 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -0700917 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
918
Christopher Tate79588342009-06-30 16:11:49 -0700919 // Backups run at background priority
920 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
921
Christopher Tate043dadc2009-06-02 16:11:00 -0700922 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700923 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -0700924
925 // If we haven't stored anything yet, we need to do an init operation.
926 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
927 status = mTransport.initializeDevice();
928 }
Dan Egnorbb9001c2009-07-27 12:20:13 -0700929
930 // The package manager doesn't have a proper <application> etc, but since
931 // it's running here in the system process we can just set up its agent
932 // directly and use a synthetic BackupRequest. We always run this pass
933 // because it's cheap and this way we guarantee that we don't get out of
934 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -0700935 if (status == BackupConstants.TRANSPORT_OK) {
936 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
937 mPackageManager, allAgentPackages());
938 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
939 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
940 status = processOneBackup(pmRequest,
941 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
942 }
Christopher Tate90967f42009-09-20 15:28:33 -0700943
Dan Egnor01445162009-09-21 17:04:05 -0700944 if (status == BackupConstants.TRANSPORT_OK) {
945 // Now run all the backups in our queue
946 status = doQueuedBackups(mTransport);
947 }
948
949 if (status == BackupConstants.TRANSPORT_OK) {
950 // Tell the transport to finish everything it has buffered
951 status = mTransport.finishBackup();
952 if (status == BackupConstants.TRANSPORT_OK) {
953 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
954 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
955 } else {
956 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
957 Log.e(TAG, "Transport error in finishBackup()");
958 }
959 }
960
Dan Egnor01445162009-09-21 17:04:05 -0700961 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -0700962 // The backend reports that our dataset has been wiped. We need to
963 // reset all of our bookkeeping and instead run a new backup pass for
964 // everything.
965 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
966 resetBackupState(mStateDir);
967 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -0700968 }
969 } catch (Exception e) {
970 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -0700971 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700972 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -0700973 // If things went wrong, we need to re-stage the apps we had expected
974 // to be backing up in this pass. This journals the package names in
975 // the current active pending-backup file, not in the we are holding
976 // here in mJournal.
977 if (status != BackupConstants.TRANSPORT_OK) {
978 Log.w(TAG, "Backup pass unsuccessful, restaging");
979 for (BackupRequest req : mQueue) {
980 try {
981 dataChanged(req.appInfo.packageName);
982 } catch (RemoteException e) {
983 // can't happen; it's a local call
984 }
985 }
986 }
987
988 // Either backup was successful, in which case we of course do not need
989 // this pass's journal any more; or it failed, in which case we just
990 // re-enqueued all of these packages in the current active journal.
991 // Either way, we no longer need this pass's journal.
992 if (!mJournal.delete()) {
993 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
994 }
995
Dan Egnorbb9001c2009-07-27 12:20:13 -0700996 // Only once we're entirely finished do we release the wakelock
997 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -0700998 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700999 }
1000
Dan Egnor01445162009-09-21 17:04:05 -07001001 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001002 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001003 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001004
Christopher Tate0749dcd2009-08-13 15:13:03 -07001005 // Don't run backup, even if requested, if the target app does not have
1006 // the requisite permission
1007 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1008 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1009 Log.w(TAG, "Skipping backup of unprivileged package "
1010 + request.appInfo.packageName);
1011 continue;
1012 }
1013
Christopher Tate043dadc2009-06-02 16:11:00 -07001014 IBackupAgent agent = null;
1015 int mode = (request.fullBackup)
1016 ? IApplicationThread.BACKUP_MODE_FULL
1017 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1018 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001019 agent = bindToAgentSynchronous(request.appInfo, mode);
1020 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001021 int result = processOneBackup(request, agent, transport);
1022 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001023 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001024 } catch (SecurityException ex) {
1025 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001026 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001027 } finally {
1028 try { // unbind even on timeout, just in case
1029 mActivityManager.unbindBackupAgent(request.appInfo);
1030 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001031 }
1032 }
Dan Egnor01445162009-09-21 17:04:05 -07001033
1034 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001035 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001036
Dan Egnor01445162009-09-21 17:04:05 -07001037 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1038 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001039 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001040 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001041
Dan Egnorbb9001c2009-07-27 12:20:13 -07001042 File savedStateName = new File(mStateDir, packageName);
1043 File backupDataName = new File(mDataDir, packageName + ".data");
1044 File newStateName = new File(mStateDir, packageName + ".new");
1045
1046 ParcelFileDescriptor savedState = null;
1047 ParcelFileDescriptor backupData = null;
1048 ParcelFileDescriptor newState = null;
1049
1050 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001051 try {
1052 // Look up the package info & signatures. This is first so that if it
1053 // throws an exception, there's no file setup yet that would need to
1054 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001055 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1056 // The metadata 'package' is synthetic
1057 packInfo = new PackageInfo();
1058 packInfo.packageName = packageName;
1059 } else {
1060 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001061 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001062 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001063
Christopher Tatec7b31e32009-06-10 15:49:30 -07001064 // In a full backup, we pass a null ParcelFileDescriptor as
1065 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001066 if (!request.fullBackup) {
1067 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001068 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001069 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1070 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001071
Dan Egnorbb9001c2009-07-27 12:20:13 -07001072 backupData = ParcelFileDescriptor.open(backupDataName,
1073 ParcelFileDescriptor.MODE_READ_WRITE |
1074 ParcelFileDescriptor.MODE_CREATE |
1075 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001076
Dan Egnorbb9001c2009-07-27 12:20:13 -07001077 newState = ParcelFileDescriptor.open(newStateName,
1078 ParcelFileDescriptor.MODE_READ_WRITE |
1079 ParcelFileDescriptor.MODE_CREATE |
1080 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001081
1082 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001083 agent.doBackup(savedState, backupData, newState);
1084 logBackupComplete(packageName);
1085 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001086 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001087 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001088 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1089 backupDataName.delete();
1090 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001091 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001092 } finally {
1093 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1094 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1095 try { if (newState != null) newState.close(); } catch (IOException e) {}
1096 savedState = backupData = newState = null;
1097 }
1098
1099 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001100 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001101 try {
1102 int size = (int) backupDataName.length();
1103 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001104 if (result == BackupConstants.TRANSPORT_OK) {
1105 backupData = ParcelFileDescriptor.open(backupDataName,
1106 ParcelFileDescriptor.MODE_READ_ONLY);
1107 result = transport.performBackup(packInfo, backupData);
1108 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001109
Dan Egnor83861e72009-09-17 16:17:55 -07001110 // TODO - We call finishBackup() for each application backed up, because
1111 // we need to know now whether it succeeded or failed. Instead, we should
1112 // hold off on finishBackup() until the end, which implies holding off on
1113 // renaming *all* the output state files (see below) until that happens.
1114
Dan Egnor01445162009-09-21 17:04:05 -07001115 if (result == BackupConstants.TRANSPORT_OK) {
1116 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001117 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001118 } else {
1119 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1120 }
1121
1122 // After successful transport, delete the now-stale data
1123 // and juggle the files so that next time we supply the agent
1124 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001125 if (result == BackupConstants.TRANSPORT_OK) {
1126 backupDataName.delete();
1127 newStateName.renameTo(savedStateName);
1128 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1129 } else {
1130 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1131 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001132 } catch (Exception e) {
1133 Log.e(TAG, "Transport error backing up " + packageName, e);
1134 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001135 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001136 } finally {
1137 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001138 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001139
Dan Egnor01445162009-09-21 17:04:05 -07001140 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001141 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001142 }
1143
Christopher Tatedf01dea2009-06-09 20:45:02 -07001144
1145 // ----- Restore handling -----
1146
Christopher Tateabce4e82009-06-18 18:35:32 -07001147 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001148 // Allow unsigned apps, but not signed on one device and unsigned on the other
1149 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001150 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1151 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001152 if ((storedSigs == null || storedSigs.length == 0)
1153 && (deviceSigs == null || deviceSigs.length == 0)) {
1154 return true;
1155 }
1156 if (storedSigs == null || deviceSigs == null) {
1157 return false;
1158 }
1159
Christopher Tateabce4e82009-06-18 18:35:32 -07001160 // !!! TODO: this demands that every stored signature match one
1161 // that is present on device, and does not demand the converse.
1162 // Is this this right policy?
1163 int nStored = storedSigs.length;
1164 int nDevice = deviceSigs.length;
1165
1166 for (int i=0; i < nStored; i++) {
1167 boolean match = false;
1168 for (int j=0; j < nDevice; j++) {
1169 if (storedSigs[i].equals(deviceSigs[j])) {
1170 match = true;
1171 break;
1172 }
1173 }
1174 if (!match) {
1175 return false;
1176 }
1177 }
1178 return true;
1179 }
1180
Christopher Tatedf01dea2009-06-09 20:45:02 -07001181 class PerformRestoreThread extends Thread {
1182 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001183 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001184 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001185 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001186
Christopher Tate5cbbf562009-06-22 16:44:51 -07001187 class RestoreRequest {
1188 public PackageInfo app;
1189 public int storedAppVersion;
1190
1191 RestoreRequest(PackageInfo _app, int _version) {
1192 app = _app;
1193 storedAppVersion = _version;
1194 }
1195 }
1196
Christopher Tate7d562ec2009-06-25 18:03:43 -07001197 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001198 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001199 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001200 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001201 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001202 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001203
1204 try {
1205 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1206 } catch (RemoteException e) {
1207 // can't happen; the transport is local
1208 }
1209 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001210 }
1211
1212 @Override
1213 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001214 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001215 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001216 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001217 /**
1218 * Restore sequence:
1219 *
Dan Egnorefe52642009-06-24 00:16:33 -07001220 * 1. get the restore set description for our identity
1221 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001222 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001223 * 3. for each app in the restore queue:
1224 * 3.a. clear the app data
1225 * 3.b. get the restore data for the app from the transport
1226 * 3.c. launch the backup agent for the app
1227 * 3.d. agent.doRestore() with the data from the server
1228 * 3.e. unbind the agent [and kill the app?]
1229 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001230 *
1231 * On errors, we try our best to recover and move on to the next
1232 * application, but if necessary we abort the whole operation --
1233 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001234 */
1235
Christopher Tate7d562ec2009-06-25 18:03:43 -07001236 int error = -1; // assume error
1237
Dan Egnorefe52642009-06-24 00:16:33 -07001238 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001239 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001240 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001241 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001242
Dan Egnorefe52642009-06-24 00:16:33 -07001243 // Get the list of all packages which have backup enabled.
1244 // (Include the Package Manager metadata pseudo-package first.)
1245 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1246 PackageInfo omPackage = new PackageInfo();
1247 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1248 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001249
Dan Egnorefe52642009-06-24 00:16:33 -07001250 List<PackageInfo> agentPackages = allAgentPackages();
1251 restorePackages.addAll(agentPackages);
1252
Christopher Tate7d562ec2009-06-25 18:03:43 -07001253 // let the observer know that we're running
1254 if (mObserver != null) {
1255 try {
1256 // !!! TODO: get an actual count from the transport after
1257 // its startRestore() runs?
1258 mObserver.restoreStarting(restorePackages.size());
1259 } catch (RemoteException e) {
1260 Log.d(TAG, "Restore observer died at restoreStarting");
1261 mObserver = null;
1262 }
1263 }
1264
Dan Egnor01445162009-09-21 17:04:05 -07001265 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1266 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001267 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001268 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001269 return;
1270 }
1271
1272 String packageName = mTransport.nextRestorePackage();
1273 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001274 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001275 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001276 return;
1277 } else if (packageName.equals("")) {
1278 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001279 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1280 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001281 return;
1282 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1283 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1284 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001285 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1286 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001287 return;
1288 }
1289
1290 // Pull the Package Manager metadata from the restore set first
1291 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1292 mPackageManager, agentPackages);
1293 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1294
Christopher Tate8c032472009-07-02 14:28:47 -07001295 // Verify that the backup set includes metadata. If not, we can't do
1296 // signature/version verification etc, so we simply do not proceed with
1297 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001298 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001299 Log.e(TAG, "No restore metadata available, so not restoring settings");
1300 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1301 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001302 return;
1303 }
1304
Christopher Tate7d562ec2009-06-25 18:03:43 -07001305 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001306 for (;;) {
1307 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308
Dan Egnorefe52642009-06-24 00:16:33 -07001309 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001310 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001311 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001312 return;
1313 } else if (packageName.equals("")) {
1314 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001315 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001316
Christopher Tate7d562ec2009-06-25 18:03:43 -07001317 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001318 try {
1319 mObserver.onUpdate(count);
1320 } catch (RemoteException e) {
1321 Log.d(TAG, "Restore observer died in onUpdate");
1322 mObserver = null;
1323 }
1324 }
1325
Dan Egnorefe52642009-06-24 00:16:33 -07001326 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1327 if (metaInfo == null) {
1328 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001329 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1330 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001331 continue;
1332 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001333
Dan Egnorbb9001c2009-07-27 12:20:13 -07001334 PackageInfo packageInfo;
1335 try {
1336 int flags = PackageManager.GET_SIGNATURES;
1337 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1338 } catch (NameNotFoundException e) {
1339 Log.e(TAG, "Invalid package restoring data", e);
1340 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1341 "Package missing on device");
1342 continue;
1343 }
1344
Dan Egnorefe52642009-06-24 00:16:33 -07001345 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001346 String message = "Version " + metaInfo.versionCode
1347 + " > installed version " + packageInfo.versionCode;
1348 Log.w(TAG, "Package " + packageName + ": " + message);
1349 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001350 continue;
1351 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001352
Dan Egnorefe52642009-06-24 00:16:33 -07001353 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1354 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001355 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1356 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001357 continue;
1358 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001359
Dan Egnorefe52642009-06-24 00:16:33 -07001360 if (DEBUG) Log.v(TAG, "Package " + packageName
1361 + " restore version [" + metaInfo.versionCode
1362 + "] is compatible with installed version ["
1363 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001364
Christopher Tate5e1ab332009-09-01 20:32:49 -07001365 // Now perform the actual restore: first clear the app's data
1366 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001367 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001368
1369 // Then set up and bind the agent (with a restricted Application object
1370 // unless the application says otherwise)
1371 boolean useRealApp = (packageInfo.applicationInfo.flags
1372 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1373 if (DEBUG && useRealApp) {
1374 Log.v(TAG, "agent requires real Application subclass for restore");
1375 }
Dan Egnorefe52642009-06-24 00:16:33 -07001376 IBackupAgent agent = bindToAgentSynchronous(
1377 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001378 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1379 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001380 if (agent == null) {
1381 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1383 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001384 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001385 }
1386
Christopher Tate5e1ab332009-09-01 20:32:49 -07001387 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001388 try {
1389 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001390 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001391 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001392 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001393 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001394
1395 // The agent was probably running with a stub Application object,
1396 // which isn't a valid run mode for the main app logic. Shut
1397 // down the app so that next time it's launched, it gets the
1398 // usual full initialization.
1399 if ((packageInfo.applicationInfo.flags
1400 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1401 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1402 + packageInfo.applicationInfo.processName);
1403 mActivityManager.killApplicationProcess(
1404 packageInfo.applicationInfo.processName,
1405 packageInfo.applicationInfo.uid);
1406 }
Dan Egnorefe52642009-06-24 00:16:33 -07001407 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001408 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001409
1410 // if we get this far, report success to the observer
1411 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001412 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1413 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1414 } catch (Exception e) {
1415 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001416 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001417 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1418
Dan Egnorefe52642009-06-24 00:16:33 -07001419 try {
1420 mTransport.finishRestore();
1421 } catch (RemoteException e) {
1422 Log.e(TAG, "Error finishing restore", e);
1423 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001424
1425 if (mObserver != null) {
1426 try {
1427 mObserver.restoreFinished(error);
1428 } catch (RemoteException e) {
1429 Log.d(TAG, "Restore observer died at restoreFinished");
1430 }
1431 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001432
1433 // done; we can finally release the wakelock
1434 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001435 }
1436 }
1437
Dan Egnorefe52642009-06-24 00:16:33 -07001438 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1439 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001440 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001441 final String packageName = app.packageName;
1442
Dan Egnorbb9001c2009-07-27 12:20:13 -07001443 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001444
Christopher Tate0749dcd2009-08-13 15:13:03 -07001445 // Don't restore to unprivileged packages
1446 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1447 packageName) != PackageManager.PERMISSION_GRANTED) {
1448 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1449 }
1450
Christopher Tatec7b31e32009-06-10 15:49:30 -07001451 // !!! TODO: get the dirs from the transport
1452 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001453 File newStateName = new File(mStateDir, packageName + ".new");
1454 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001455
Dan Egnorbb9001c2009-07-27 12:20:13 -07001456 ParcelFileDescriptor backupData = null;
1457 ParcelFileDescriptor newState = null;
1458
1459 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001460 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001461 backupData = ParcelFileDescriptor.open(backupDataName,
1462 ParcelFileDescriptor.MODE_READ_WRITE |
1463 ParcelFileDescriptor.MODE_CREATE |
1464 ParcelFileDescriptor.MODE_TRUNCATE);
1465
Dan Egnor01445162009-09-21 17:04:05 -07001466 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001467 Log.e(TAG, "Error getting restore data for " + packageName);
1468 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1469 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001470 }
1471
1472 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001473 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001474 backupData = ParcelFileDescriptor.open(backupDataName,
1475 ParcelFileDescriptor.MODE_READ_ONLY);
1476
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477 newState = ParcelFileDescriptor.open(newStateName,
1478 ParcelFileDescriptor.MODE_READ_WRITE |
1479 ParcelFileDescriptor.MODE_CREATE |
1480 ParcelFileDescriptor.MODE_TRUNCATE);
1481
1482 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001483
1484 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001485 //
1486 // !!! TODO: the restored data should be migrated on the server
1487 // side into the current dataset. In that case the new state file
1488 // we just created would reflect the data already extant in the
1489 // backend, so there'd be nothing more to do. Until that happens,
1490 // however, we need to make sure that we record the data to the
1491 // current backend dataset. (Yes, this means shipping the data over
1492 // the wire in both directions. That's bad, but consistency comes
1493 // first, then efficiency.) Once we introduce server-side data
1494 // migration to the newly-restored device's dataset, we will change
1495 // the following from a discard of the newly-written state to the
1496 // "correct" operation of renaming into the canonical state blob.
1497 newStateName.delete(); // TODO: remove; see above comment
1498 //newStateName.renameTo(savedStateName); // TODO: replace with this
1499
Dan Egnorbb9001c2009-07-27 12:20:13 -07001500 int size = (int) backupDataName.length();
1501 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001502 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001503 Log.e(TAG, "Error restoring data for " + packageName, e);
1504 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1505
Christopher Tate96733042009-07-20 14:49:13 -07001506 // If the agent fails restore, it might have put the app's data
1507 // into an incoherent state. For consistency we wipe its data
1508 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001509 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001510 } finally {
1511 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001512 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1513 try { if (newState != null) newState.close(); } catch (IOException e) {}
1514 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001515 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001516 }
1517 }
1518
Christopher Tateee0e78a2009-07-02 11:17:03 -07001519 class PerformClearThread extends Thread {
1520 IBackupTransport mTransport;
1521 PackageInfo mPackage;
1522
1523 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1524 mTransport = transport;
1525 mPackage = packageInfo;
1526 }
1527
1528 @Override
1529 public void run() {
1530 try {
1531 // Clear the on-device backup state to ensure a full backup next time
1532 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1533 File stateFile = new File(stateDir, mPackage.packageName);
1534 stateFile.delete();
1535
1536 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001537 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001538 mTransport.clearBackupData(mPackage);
1539 } catch (RemoteException e) {
1540 // can't happen; the transport is local
1541 } finally {
1542 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001543 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001544 mTransport.finishBackup();
1545 } catch (RemoteException e) {
1546 // can't happen; the transport is local
1547 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001548
1549 // Last but not least, release the cpu
1550 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001551 }
1552 }
1553 }
1554
Christopher Tatedf01dea2009-06-09 20:45:02 -07001555
Christopher Tate487529a2009-04-29 14:03:25 -07001556 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001557
Christopher Tatea8bf8152009-04-30 11:36:21 -07001558 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001559 // Record that we need a backup pass for the caller. Since multiple callers
1560 // may share a uid, we need to note all candidates within that uid and schedule
1561 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001562 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001563
Christopher Tate63d27002009-06-16 17:16:42 -07001564 // If the caller does not hold the BACKUP permission, it can only request a
1565 // backup of its own data.
1566 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001567 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001568 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1569 targets = mBackupParticipants.get(Binder.getCallingUid());
1570 } else {
1571 // a caller with full permission can ask to back up any participating app
1572 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001573 targets = new HashSet<ApplicationInfo>();
1574 int N = mBackupParticipants.size();
1575 for (int i = 0; i < N; i++) {
1576 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1577 if (s != null) {
1578 targets.addAll(s);
1579 }
1580 }
1581 }
Christopher Tate487529a2009-04-29 14:03:25 -07001582 if (targets != null) {
1583 synchronized (mQueueLock) {
1584 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001585 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001586 // validate the caller-supplied package name against the known set of
1587 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001588 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001589 // Add the caller to the set of pending backups. If there is
1590 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001591 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001592 if (mPendingBackups.put(app, req) == null) {
1593 // Journal this request in case of crash. The put()
1594 // operation returned null when this package was not already
1595 // in the set; we want to avoid touching the disk redundantly.
1596 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001597
Christopher Tate22b60d82009-07-07 16:36:02 -07001598 if (DEBUG) {
1599 int numKeys = mPendingBackups.size();
1600 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1601 for (BackupRequest b : mPendingBackups.values()) {
1602 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1603 }
1604 }
1605 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001606 }
1607 }
Christopher Tate487529a2009-04-29 14:03:25 -07001608 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001609 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001610 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1611 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001612 }
1613 }
Christopher Tate46758122009-05-06 11:22:00 -07001614
Christopher Tatecde87f42009-06-12 12:55:53 -07001615 private void writeToJournalLocked(String str) {
1616 if (mJournalStream != null) {
1617 try {
1618 mJournalStream.writeUTF(str);
1619 } catch (IOException e) {
1620 Log.e(TAG, "Error writing to backup journal");
1621 mJournalStream = null;
1622 mJournal = null;
1623 }
1624 }
1625 }
1626
Christopher Tateee0e78a2009-07-02 11:17:03 -07001627 // Clear the given package's backup data from the current transport
1628 public void clearBackupData(String packageName) {
1629 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1630 PackageInfo info;
1631 try {
1632 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1633 } catch (NameNotFoundException e) {
1634 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1635 return;
1636 }
1637
1638 // If the caller does not hold the BACKUP permission, it can only request a
1639 // wipe of its own backed-up data.
1640 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001641 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001642 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1643 apps = mBackupParticipants.get(Binder.getCallingUid());
1644 } else {
1645 // a caller with full permission can ask to back up any participating app
1646 // !!! TODO: allow data-clear of ANY app?
1647 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1648 apps = new HashSet<ApplicationInfo>();
1649 int N = mBackupParticipants.size();
1650 for (int i = 0; i < N; i++) {
1651 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1652 if (s != null) {
1653 apps.addAll(s);
1654 }
1655 }
1656 }
1657
1658 // now find the given package in the set of candidate apps
1659 for (ApplicationInfo app : apps) {
1660 if (app.packageName.equals(packageName)) {
1661 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1662 // found it; fire off the clear request
1663 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001664 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001665 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001666 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1667 new ClearParams(getTransport(mCurrentTransport), info));
1668 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001669 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001670 }
1671 break;
1672 }
1673 }
1674 }
1675
Christopher Tateace7f092009-06-15 18:07:25 -07001676 // Run a backup pass immediately for any applications that have declared
1677 // that they have pending updates.
1678 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001680
Christopher Tateace7f092009-06-15 18:07:25 -07001681 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001682 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001683 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001684 mRunBackupIntent.send();
1685 } catch (PendingIntent.CanceledException e) {
1686 // should never happen
1687 Log.e(TAG, "run-backup intent cancelled!");
1688 }
Christopher Tate46758122009-05-06 11:22:00 -07001689 }
1690 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001691
Christopher Tate8031a3d2009-07-06 16:36:05 -07001692 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001693 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001694 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1695 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001696
1697 boolean wasEnabled = mEnabled;
1698 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001699 Settings.Secure.putInt(mContext.getContentResolver(),
1700 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001701 mEnabled = enable;
1702 }
1703
Christopher Tate49401dd2009-07-01 12:34:29 -07001704 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001705 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001706 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001707 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001708 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001709 // No longer enabled, so stop running backups
1710 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001711 }
1712 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001713 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001714
Christopher Tate8031a3d2009-07-06 16:36:05 -07001715 // Mark the backup service as having been provisioned
1716 public void setBackupProvisioned(boolean available) {
1717 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1718 "setBackupProvisioned");
1719
1720 boolean wasProvisioned = mProvisioned;
1721 synchronized (this) {
1722 Settings.Secure.putInt(mContext.getContentResolver(),
1723 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1724 mProvisioned = available;
1725 }
1726
1727 synchronized (mQueueLock) {
1728 if (available && !wasProvisioned && mEnabled) {
1729 // we're now good to go, so start the backup alarms
1730 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1731 } else if (!available) {
1732 // No longer enabled, so stop running backups
1733 Log.w(TAG, "Backup service no longer provisioned");
1734 mAlarmManager.cancel(mRunBackupIntent);
1735 }
1736 }
1737 }
1738
1739 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1740 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1741 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1742 BACKUP_INTERVAL, mRunBackupIntent);
1743 }
1744
Christopher Tate6ef58a12009-06-29 14:56:28 -07001745 // Report whether the backup mechanism is currently enabled
1746 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001747 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001748 return mEnabled; // no need to synchronize just to read it
1749 }
1750
Christopher Tate91717492009-06-26 21:07:13 -07001751 // Report the name of the currently active transport
1752 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001754 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001755 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001756 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001757 }
1758
Christopher Tate91717492009-06-26 21:07:13 -07001759 // Report all known, available backup transports
1760 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001762
Christopher Tate91717492009-06-26 21:07:13 -07001763 String[] list = null;
1764 ArrayList<String> known = new ArrayList<String>();
1765 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1766 if (entry.getValue() != null) {
1767 known.add(entry.getKey());
1768 }
1769 }
1770
1771 if (known.size() > 0) {
1772 list = new String[known.size()];
1773 known.toArray(list);
1774 }
1775 return list;
1776 }
1777
1778 // Select which transport to use for the next backup operation. If the given
1779 // name is not one of the available transports, no action is taken and the method
1780 // returns null.
1781 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001783
1784 synchronized (mTransports) {
1785 String prevTransport = null;
1786 if (mTransports.get(transport) != null) {
1787 prevTransport = mCurrentTransport;
1788 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001789 Settings.Secure.putString(mContext.getContentResolver(),
1790 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001791 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1792 + " returning " + prevTransport);
1793 } else {
1794 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1795 }
1796 return prevTransport;
1797 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001798 }
1799
1800 // Callback: a requested backup agent has been instantiated. This should only
1801 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001802 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001803 synchronized(mAgentConnectLock) {
1804 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1805 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1806 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1807 mConnectedAgent = agent;
1808 mConnecting = false;
1809 } else {
1810 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1811 + " claiming agent connected");
1812 }
1813 mAgentConnectLock.notifyAll();
1814 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001815 }
1816
1817 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1818 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001819 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001820 public void agentDisconnected(String packageName) {
1821 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001822 synchronized(mAgentConnectLock) {
1823 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1824 mConnectedAgent = null;
1825 mConnecting = false;
1826 } else {
1827 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1828 + " claiming agent disconnected");
1829 }
1830 mAgentConnectLock.notifyAll();
1831 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001832 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001833
Christopher Tate8c850b72009-06-07 19:33:20 -07001834 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001835 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001837
1838 synchronized(this) {
1839 if (mActiveRestoreSession != null) {
1840 Log.d(TAG, "Restore session requested but one already active");
1841 return null;
1842 }
Christopher Tate91717492009-06-26 21:07:13 -07001843 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001844 }
1845 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001846 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001847
Christopher Tate9b3905c2009-06-08 15:24:01 -07001848 // ----- Restore session -----
1849
1850 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001851 private static final String TAG = "RestoreSession";
1852
Christopher Tate9b3905c2009-06-08 15:24:01 -07001853 private IBackupTransport mRestoreTransport = null;
1854 RestoreSet[] mRestoreSets = null;
1855
Christopher Tate91717492009-06-26 21:07:13 -07001856 RestoreSession(String transport) {
1857 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001858 }
1859
1860 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07001861 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04001862 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001863 "getAvailableRestoreSets");
1864
Christopher Tatef68eb502009-06-16 11:02:01 -07001865 try {
Christopher Tate43383042009-07-13 15:17:13 -07001866 if (mRestoreTransport == null) {
1867 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07001868 return null;
1869 }
1870 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001871 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001872 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001873 }
1874 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07001875 } catch (Exception e) {
1876 Log.e(TAG, "Error in getAvailableRestoreSets", e);
1877 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001878 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001879 }
1880
Dan Egnor0084da52009-07-29 12:57:16 -07001881 public synchronized int performRestore(long token, IRestoreObserver observer) {
1882 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1883 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001884
Christopher Tatef2c321a2009-08-10 15:43:36 -07001885 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
1886 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001887
Dan Egnor0084da52009-07-29 12:57:16 -07001888 if (mRestoreTransport == null || mRestoreSets == null) {
1889 Log.e(TAG, "Ignoring performRestore() with no restore set");
1890 return -1;
1891 }
1892
1893 for (int i = 0; i < mRestoreSets.length; i++) {
1894 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001895 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07001896 mWakelock.acquire();
1897 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1898 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
1899 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001900 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07001901 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001902 }
1903 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07001904
1905 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07001906 return -1;
1907 }
1908
Dan Egnor0084da52009-07-29 12:57:16 -07001909 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04001910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001911 "endRestoreSession");
1912
Dan Egnor0084da52009-07-29 12:57:16 -07001913 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001914
Dan Egnor0084da52009-07-29 12:57:16 -07001915 synchronized (this) {
1916 try {
1917 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
1918 } catch (Exception e) {
1919 Log.e(TAG, "Error in finishRestore", e);
1920 } finally {
1921 mRestoreTransport = null;
1922 }
1923 }
1924
1925 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07001926 if (BackupManagerService.this.mActiveRestoreSession == this) {
1927 BackupManagerService.this.mActiveRestoreSession = null;
1928 } else {
1929 Log.e(TAG, "ending non-current restore session");
1930 }
1931 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001932 }
1933 }
1934
Christopher Tate043dadc2009-06-02 16:11:00 -07001935
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001936 @Override
1937 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1938 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001939 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1940 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001941 pw.println("Available transports:");
1942 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001943 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1944 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001945 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001946 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001947 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001948 for (int i=0; i<N; i++) {
1949 int uid = mBackupParticipants.keyAt(i);
1950 pw.print(" uid: ");
1951 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001952 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1953 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001954 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001955 }
1956 }
Christopher Tate73e02522009-07-15 14:18:26 -07001957 pw.println("Ever backed up: " + mEverStoredApps.size());
1958 for (String pkg : mEverStoredApps) {
1959 pw.println(" " + pkg);
1960 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001961 pw.println("Pending: " + mPendingBackups.size());
1962 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001963 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001964 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001965 }
1966 }
Christopher Tate487529a2009-04-29 14:03:25 -07001967}