blob: 861f66d0144ac4c2d8813fd6bc548a2fdc7b39a3 [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() {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700915 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -0700916 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
917
Christopher Tate79588342009-06-30 16:11:49 -0700918 // Backups run at background priority
919 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
920
Christopher Tate043dadc2009-06-02 16:11:00 -0700921 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700922 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
923
924 // The package manager doesn't have a proper <application> etc, but since
925 // it's running here in the system process we can just set up its agent
926 // directly and use a synthetic BackupRequest. We always run this pass
927 // because it's cheap and this way we guarantee that we don't get out of
928 // step even if we're selecting among various transports at run time.
929 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
930 mPackageManager, allAgentPackages());
931 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
932 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate90967f42009-09-20 15:28:33 -0700933
934 // If we haven't stored anything yet, we need to do an init
935 // operation along with recording the metadata blob.
936 boolean needInit = (mEverStoredApps.size() == 0);
Christopher Tated55e18a2009-09-21 10:12:59 -0700937 int result = processOneBackup(pmRequest,
938 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
Christopher Tate90967f42009-09-20 15:28:33 -0700939 mTransport, needInit);
Christopher Tated55e18a2009-09-21 10:12:59 -0700940 if (result == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
941 // The backend reports that our dataset has been wiped. We need to
942 // reset all of our bookkeeping and instead run a new backup pass for
943 // everything.
944 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
945 resetBackupState(mStateDir);
946 backupNow();
947 return;
948 } else if (result != BackupConstants.TRANSPORT_OK) {
949 // Give up if we couldn't even process the metadata
950 Log.e(TAG, "Meta backup err " + result);
951 return;
952 }
Dan Egnorbb9001c2009-07-27 12:20:13 -0700953
954 // Now run all the backups in our queue
955 int count = mQueue.size();
956 doQueuedBackups(mTransport);
957
958 // Finally, tear down the transport
959 if (mTransport.finishBackup()) {
960 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
961 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, count, millis);
962 } else {
963 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
964 Log.e(TAG, "Transport error in finishBackup()");
Dan Egnorefe52642009-06-24 00:16:33 -0700965 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700966
Dan Egnorbb9001c2009-07-27 12:20:13 -0700967 if (!mJournal.delete()) {
968 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
969 }
970 } catch (Exception e) {
971 Log.e(TAG, "Error in backup thread", e);
972 } finally {
973 // Only once we're entirely finished do we release the wakelock
974 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -0700975 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700976 }
977
978 private void doQueuedBackups(IBackupTransport transport) {
979 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700980 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700981
Christopher Tate0749dcd2009-08-13 15:13:03 -0700982 // Don't run backup, even if requested, if the target app does not have
983 // the requisite permission
984 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
985 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
986 Log.w(TAG, "Skipping backup of unprivileged package "
987 + request.appInfo.packageName);
988 continue;
989 }
990
Christopher Tate043dadc2009-06-02 16:11:00 -0700991 IBackupAgent agent = null;
992 int mode = (request.fullBackup)
993 ? IApplicationThread.BACKUP_MODE_FULL
994 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
995 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700996 agent = bindToAgentSynchronous(request.appInfo, mode);
997 if (agent != null) {
Christopher Tate90967f42009-09-20 15:28:33 -0700998 processOneBackup(request, agent, transport, false);
Christopher Tate043dadc2009-06-02 16:11:00 -0700999 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001000
1001 // unbind even on timeout, just in case
1002 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -07001003 } catch (SecurityException ex) {
1004 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001005 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -07001006 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001007 Log.v(TAG, "bind/backup threw");
1008 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -07001009 }
1010 }
1011 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001012
Christopher Tated55e18a2009-09-21 10:12:59 -07001013 int processOneBackup(BackupRequest request, IBackupAgent agent,
Christopher Tate90967f42009-09-20 15:28:33 -07001014 IBackupTransport transport, boolean doInit) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001015 final String packageName = request.appInfo.packageName;
Christopher Tate90967f42009-09-20 15:28:33 -07001016 if (DEBUG) Log.d(TAG, "processOneBackup doBackup(" + doInit + ") on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001017
Dan Egnorbb9001c2009-07-27 12:20:13 -07001018 File savedStateName = new File(mStateDir, packageName);
1019 File backupDataName = new File(mDataDir, packageName + ".data");
1020 File newStateName = new File(mStateDir, packageName + ".new");
1021
1022 ParcelFileDescriptor savedState = null;
1023 ParcelFileDescriptor backupData = null;
1024 ParcelFileDescriptor newState = null;
1025
1026 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001027 try {
1028 // Look up the package info & signatures. This is first so that if it
1029 // throws an exception, there's no file setup yet that would need to
1030 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001031 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1032 // The metadata 'package' is synthetic
1033 packInfo = new PackageInfo();
1034 packInfo.packageName = packageName;
1035 } else {
1036 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001037 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001038 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001039
Christopher Tatec7b31e32009-06-10 15:49:30 -07001040 // In a full backup, we pass a null ParcelFileDescriptor as
1041 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001042 if (!request.fullBackup) {
1043 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001044 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001045 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1046 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001047
Dan Egnorbb9001c2009-07-27 12:20:13 -07001048 backupData = ParcelFileDescriptor.open(backupDataName,
1049 ParcelFileDescriptor.MODE_READ_WRITE |
1050 ParcelFileDescriptor.MODE_CREATE |
1051 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001052
Dan Egnorbb9001c2009-07-27 12:20:13 -07001053 newState = ParcelFileDescriptor.open(newStateName,
1054 ParcelFileDescriptor.MODE_READ_WRITE |
1055 ParcelFileDescriptor.MODE_CREATE |
1056 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001057
1058 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001059 agent.doBackup(savedState, backupData, newState);
1060 logBackupComplete(packageName);
1061 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001062 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001063 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001064 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1065 backupDataName.delete();
1066 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001067 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001068 } finally {
1069 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1070 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1071 try { if (newState != null) newState.close(); } catch (IOException e) {}
1072 savedState = backupData = newState = null;
1073 }
1074
1075 // Now propagate the newly-backed-up data to the transport
1076 try {
1077 int size = (int) backupDataName.length();
1078 if (size > 0) {
1079 backupData = ParcelFileDescriptor.open(backupDataName,
1080 ParcelFileDescriptor.MODE_READ_ONLY);
1081
Dan Egnor83861e72009-09-17 16:17:55 -07001082 // TODO - We call finishBackup() for each application backed up, because
1083 // we need to know now whether it succeeded or failed. Instead, we should
1084 // hold off on finishBackup() until the end, which implies holding off on
1085 // renaming *all* the output state files (see below) until that happens.
1086
Christopher Tated55e18a2009-09-21 10:12:59 -07001087 int performOkay = transport.performBackup(packInfo, backupData, doInit);
1088 if (performOkay == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1089 Log.i(TAG, "Backend not initialized");
1090 return performOkay;
1091 }
1092
1093 if ((performOkay != 0) ||
Dan Egnor83861e72009-09-17 16:17:55 -07001094 !transport.finishBackup()) {
1095 throw new Exception("Backup transport failed");
1096 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001097 } else {
1098 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1099 }
1100
1101 // After successful transport, delete the now-stale data
1102 // and juggle the files so that next time we supply the agent
1103 // with the new state file it just created.
1104 backupDataName.delete();
1105 newStateName.renameTo(savedStateName);
1106 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1107 } catch (Exception e) {
1108 Log.e(TAG, "Transport error backing up " + packageName, e);
1109 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -07001110 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001111 } finally {
1112 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001113 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001114
1115 return BackupConstants.TRANSPORT_OK;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001116 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001117 }
1118
Christopher Tatedf01dea2009-06-09 20:45:02 -07001119
1120 // ----- Restore handling -----
1121
Christopher Tateabce4e82009-06-18 18:35:32 -07001122 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001123 // Allow unsigned apps, but not signed on one device and unsigned on the other
1124 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001125 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1126 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001127 if ((storedSigs == null || storedSigs.length == 0)
1128 && (deviceSigs == null || deviceSigs.length == 0)) {
1129 return true;
1130 }
1131 if (storedSigs == null || deviceSigs == null) {
1132 return false;
1133 }
1134
Christopher Tateabce4e82009-06-18 18:35:32 -07001135 // !!! TODO: this demands that every stored signature match one
1136 // that is present on device, and does not demand the converse.
1137 // Is this this right policy?
1138 int nStored = storedSigs.length;
1139 int nDevice = deviceSigs.length;
1140
1141 for (int i=0; i < nStored; i++) {
1142 boolean match = false;
1143 for (int j=0; j < nDevice; j++) {
1144 if (storedSigs[i].equals(deviceSigs[j])) {
1145 match = true;
1146 break;
1147 }
1148 }
1149 if (!match) {
1150 return false;
1151 }
1152 }
1153 return true;
1154 }
1155
Christopher Tatedf01dea2009-06-09 20:45:02 -07001156 class PerformRestoreThread extends Thread {
1157 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001158 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001159 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001160 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001161
Christopher Tate5cbbf562009-06-22 16:44:51 -07001162 class RestoreRequest {
1163 public PackageInfo app;
1164 public int storedAppVersion;
1165
1166 RestoreRequest(PackageInfo _app, int _version) {
1167 app = _app;
1168 storedAppVersion = _version;
1169 }
1170 }
1171
Christopher Tate7d562ec2009-06-25 18:03:43 -07001172 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001173 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001174 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001175 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001176 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001177 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001178
1179 try {
1180 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1181 } catch (RemoteException e) {
1182 // can't happen; the transport is local
1183 }
1184 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001185 }
1186
1187 @Override
1188 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001189 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001190 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001191 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001192 /**
1193 * Restore sequence:
1194 *
Dan Egnorefe52642009-06-24 00:16:33 -07001195 * 1. get the restore set description for our identity
1196 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001197 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001198 * 3. for each app in the restore queue:
1199 * 3.a. clear the app data
1200 * 3.b. get the restore data for the app from the transport
1201 * 3.c. launch the backup agent for the app
1202 * 3.d. agent.doRestore() with the data from the server
1203 * 3.e. unbind the agent [and kill the app?]
1204 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001205 *
1206 * On errors, we try our best to recover and move on to the next
1207 * application, but if necessary we abort the whole operation --
1208 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001209 */
1210
Christopher Tate7d562ec2009-06-25 18:03:43 -07001211 int error = -1; // assume error
1212
Dan Egnorefe52642009-06-24 00:16:33 -07001213 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001214 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001215 // TODO: Log this before getAvailableRestoreSets, somehow
1216 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName());
Christopher Tateabce4e82009-06-18 18:35:32 -07001217
Dan Egnorefe52642009-06-24 00:16:33 -07001218 // Get the list of all packages which have backup enabled.
1219 // (Include the Package Manager metadata pseudo-package first.)
1220 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1221 PackageInfo omPackage = new PackageInfo();
1222 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1223 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001224
Dan Egnorefe52642009-06-24 00:16:33 -07001225 List<PackageInfo> agentPackages = allAgentPackages();
1226 restorePackages.addAll(agentPackages);
1227
Christopher Tate7d562ec2009-06-25 18:03:43 -07001228 // let the observer know that we're running
1229 if (mObserver != null) {
1230 try {
1231 // !!! TODO: get an actual count from the transport after
1232 // its startRestore() runs?
1233 mObserver.restoreStarting(restorePackages.size());
1234 } catch (RemoteException e) {
1235 Log.d(TAG, "Restore observer died at restoreStarting");
1236 mObserver = null;
1237 }
1238 }
1239
Dan Egnor156411d2009-06-26 13:20:02 -07001240 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -07001241 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001242 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001243 return;
1244 }
1245
1246 String packageName = mTransport.nextRestorePackage();
1247 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001248 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001249 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001250 return;
1251 } else if (packageName.equals("")) {
1252 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001253 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1254 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001255 return;
1256 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1257 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1258 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001259 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1260 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001261 return;
1262 }
1263
1264 // Pull the Package Manager metadata from the restore set first
1265 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1266 mPackageManager, agentPackages);
1267 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1268
Christopher Tate8c032472009-07-02 14:28:47 -07001269 // Verify that the backup set includes metadata. If not, we can't do
1270 // signature/version verification etc, so we simply do not proceed with
1271 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001272 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001273 Log.e(TAG, "No restore metadata available, so not restoring settings");
1274 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1275 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001276 return;
1277 }
1278
Christopher Tate7d562ec2009-06-25 18:03:43 -07001279 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001280 for (;;) {
1281 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001282
Dan Egnorefe52642009-06-24 00:16:33 -07001283 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001284 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001285 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001286 return;
1287 } else if (packageName.equals("")) {
1288 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001289 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001290
Christopher Tate7d562ec2009-06-25 18:03:43 -07001291 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001292 try {
1293 mObserver.onUpdate(count);
1294 } catch (RemoteException e) {
1295 Log.d(TAG, "Restore observer died in onUpdate");
1296 mObserver = null;
1297 }
1298 }
1299
Dan Egnorefe52642009-06-24 00:16:33 -07001300 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1301 if (metaInfo == null) {
1302 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001303 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1304 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001305 continue;
1306 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001307
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308 PackageInfo packageInfo;
1309 try {
1310 int flags = PackageManager.GET_SIGNATURES;
1311 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1312 } catch (NameNotFoundException e) {
1313 Log.e(TAG, "Invalid package restoring data", e);
1314 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1315 "Package missing on device");
1316 continue;
1317 }
1318
Dan Egnorefe52642009-06-24 00:16:33 -07001319 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001320 String message = "Version " + metaInfo.versionCode
1321 + " > installed version " + packageInfo.versionCode;
1322 Log.w(TAG, "Package " + packageName + ": " + message);
1323 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001324 continue;
1325 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001326
Dan Egnorefe52642009-06-24 00:16:33 -07001327 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1328 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001329 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1330 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001331 continue;
1332 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001333
Dan Egnorefe52642009-06-24 00:16:33 -07001334 if (DEBUG) Log.v(TAG, "Package " + packageName
1335 + " restore version [" + metaInfo.versionCode
1336 + "] is compatible with installed version ["
1337 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001338
Christopher Tate5e1ab332009-09-01 20:32:49 -07001339 // Now perform the actual restore: first clear the app's data
1340 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001341 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001342
1343 // Then set up and bind the agent (with a restricted Application object
1344 // unless the application says otherwise)
1345 boolean useRealApp = (packageInfo.applicationInfo.flags
1346 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1347 if (DEBUG && useRealApp) {
1348 Log.v(TAG, "agent requires real Application subclass for restore");
1349 }
Dan Egnorefe52642009-06-24 00:16:33 -07001350 IBackupAgent agent = bindToAgentSynchronous(
1351 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001352 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1353 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001354 if (agent == null) {
1355 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001356 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1357 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001358 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001359 }
1360
Christopher Tate5e1ab332009-09-01 20:32:49 -07001361 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001362 try {
1363 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001364 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001365 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001366 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001367 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001368
1369 // The agent was probably running with a stub Application object,
1370 // which isn't a valid run mode for the main app logic. Shut
1371 // down the app so that next time it's launched, it gets the
1372 // usual full initialization.
1373 if ((packageInfo.applicationInfo.flags
1374 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1375 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1376 + packageInfo.applicationInfo.processName);
1377 mActivityManager.killApplicationProcess(
1378 packageInfo.applicationInfo.processName,
1379 packageInfo.applicationInfo.uid);
1380 }
Dan Egnorefe52642009-06-24 00:16:33 -07001381 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001382 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001383
1384 // if we get this far, report success to the observer
1385 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001386 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1387 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1388 } catch (Exception e) {
1389 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001390 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001391 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1392
Dan Egnorefe52642009-06-24 00:16:33 -07001393 try {
1394 mTransport.finishRestore();
1395 } catch (RemoteException e) {
1396 Log.e(TAG, "Error finishing restore", e);
1397 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001398
1399 if (mObserver != null) {
1400 try {
1401 mObserver.restoreFinished(error);
1402 } catch (RemoteException e) {
1403 Log.d(TAG, "Restore observer died at restoreFinished");
1404 }
1405 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001406
1407 // done; we can finally release the wakelock
1408 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001409 }
1410 }
1411
Dan Egnorefe52642009-06-24 00:16:33 -07001412 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1413 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001414 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001415 final String packageName = app.packageName;
1416
Dan Egnorbb9001c2009-07-27 12:20:13 -07001417 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001418
Christopher Tate0749dcd2009-08-13 15:13:03 -07001419 // Don't restore to unprivileged packages
1420 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1421 packageName) != PackageManager.PERMISSION_GRANTED) {
1422 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1423 }
1424
Christopher Tatec7b31e32009-06-10 15:49:30 -07001425 // !!! TODO: get the dirs from the transport
1426 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001427 File newStateName = new File(mStateDir, packageName + ".new");
1428 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001429
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430 ParcelFileDescriptor backupData = null;
1431 ParcelFileDescriptor newState = null;
1432
1433 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001434 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001435 backupData = ParcelFileDescriptor.open(backupDataName,
1436 ParcelFileDescriptor.MODE_READ_WRITE |
1437 ParcelFileDescriptor.MODE_CREATE |
1438 ParcelFileDescriptor.MODE_TRUNCATE);
1439
1440 if (!mTransport.getRestoreData(backupData)) {
1441 Log.e(TAG, "Error getting restore data for " + packageName);
1442 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1443 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001444 }
1445
1446 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001447 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001448 backupData = ParcelFileDescriptor.open(backupDataName,
1449 ParcelFileDescriptor.MODE_READ_ONLY);
1450
Dan Egnorbb9001c2009-07-27 12:20:13 -07001451 newState = ParcelFileDescriptor.open(newStateName,
1452 ParcelFileDescriptor.MODE_READ_WRITE |
1453 ParcelFileDescriptor.MODE_CREATE |
1454 ParcelFileDescriptor.MODE_TRUNCATE);
1455
1456 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001457
1458 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001459 //
1460 // !!! TODO: the restored data should be migrated on the server
1461 // side into the current dataset. In that case the new state file
1462 // we just created would reflect the data already extant in the
1463 // backend, so there'd be nothing more to do. Until that happens,
1464 // however, we need to make sure that we record the data to the
1465 // current backend dataset. (Yes, this means shipping the data over
1466 // the wire in both directions. That's bad, but consistency comes
1467 // first, then efficiency.) Once we introduce server-side data
1468 // migration to the newly-restored device's dataset, we will change
1469 // the following from a discard of the newly-written state to the
1470 // "correct" operation of renaming into the canonical state blob.
1471 newStateName.delete(); // TODO: remove; see above comment
1472 //newStateName.renameTo(savedStateName); // TODO: replace with this
1473
Dan Egnorbb9001c2009-07-27 12:20:13 -07001474 int size = (int) backupDataName.length();
1475 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001476 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477 Log.e(TAG, "Error restoring data for " + packageName, e);
1478 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1479
Christopher Tate96733042009-07-20 14:49:13 -07001480 // If the agent fails restore, it might have put the app's data
1481 // into an incoherent state. For consistency we wipe its data
1482 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001483 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001484 } finally {
1485 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001486 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1487 try { if (newState != null) newState.close(); } catch (IOException e) {}
1488 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001489 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001490 }
1491 }
1492
Christopher Tateee0e78a2009-07-02 11:17:03 -07001493 class PerformClearThread extends Thread {
1494 IBackupTransport mTransport;
1495 PackageInfo mPackage;
1496
1497 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1498 mTransport = transport;
1499 mPackage = packageInfo;
1500 }
1501
1502 @Override
1503 public void run() {
1504 try {
1505 // Clear the on-device backup state to ensure a full backup next time
1506 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1507 File stateFile = new File(stateDir, mPackage.packageName);
1508 stateFile.delete();
1509
1510 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001511 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001512 mTransport.clearBackupData(mPackage);
1513 } catch (RemoteException e) {
1514 // can't happen; the transport is local
1515 } finally {
1516 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001517 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001518 mTransport.finishBackup();
1519 } catch (RemoteException e) {
1520 // can't happen; the transport is local
1521 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001522
1523 // Last but not least, release the cpu
1524 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001525 }
1526 }
1527 }
1528
Christopher Tatedf01dea2009-06-09 20:45:02 -07001529
Christopher Tate487529a2009-04-29 14:03:25 -07001530 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001531
Christopher Tatea8bf8152009-04-30 11:36:21 -07001532 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001533 // Record that we need a backup pass for the caller. Since multiple callers
1534 // may share a uid, we need to note all candidates within that uid and schedule
1535 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001536 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001537
Christopher Tate63d27002009-06-16 17:16:42 -07001538 // If the caller does not hold the BACKUP permission, it can only request a
1539 // backup of its own data.
1540 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001541 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001542 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1543 targets = mBackupParticipants.get(Binder.getCallingUid());
1544 } else {
1545 // a caller with full permission can ask to back up any participating app
1546 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001547 targets = new HashSet<ApplicationInfo>();
1548 int N = mBackupParticipants.size();
1549 for (int i = 0; i < N; i++) {
1550 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1551 if (s != null) {
1552 targets.addAll(s);
1553 }
1554 }
1555 }
Christopher Tate487529a2009-04-29 14:03:25 -07001556 if (targets != null) {
1557 synchronized (mQueueLock) {
1558 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001559 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001560 // validate the caller-supplied package name against the known set of
1561 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001562 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001563 // Add the caller to the set of pending backups. If there is
1564 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001565 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001566 if (mPendingBackups.put(app, req) == null) {
1567 // Journal this request in case of crash. The put()
1568 // operation returned null when this package was not already
1569 // in the set; we want to avoid touching the disk redundantly.
1570 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001571
Christopher Tate22b60d82009-07-07 16:36:02 -07001572 if (DEBUG) {
1573 int numKeys = mPendingBackups.size();
1574 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1575 for (BackupRequest b : mPendingBackups.values()) {
1576 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1577 }
1578 }
1579 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001580 }
1581 }
Christopher Tate487529a2009-04-29 14:03:25 -07001582 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001583 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001584 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1585 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001586 }
1587 }
Christopher Tate46758122009-05-06 11:22:00 -07001588
Christopher Tatecde87f42009-06-12 12:55:53 -07001589 private void writeToJournalLocked(String str) {
1590 if (mJournalStream != null) {
1591 try {
1592 mJournalStream.writeUTF(str);
1593 } catch (IOException e) {
1594 Log.e(TAG, "Error writing to backup journal");
1595 mJournalStream = null;
1596 mJournal = null;
1597 }
1598 }
1599 }
1600
Christopher Tateee0e78a2009-07-02 11:17:03 -07001601 // Clear the given package's backup data from the current transport
1602 public void clearBackupData(String packageName) {
1603 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1604 PackageInfo info;
1605 try {
1606 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1607 } catch (NameNotFoundException e) {
1608 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1609 return;
1610 }
1611
1612 // If the caller does not hold the BACKUP permission, it can only request a
1613 // wipe of its own backed-up data.
1614 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001615 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001616 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1617 apps = mBackupParticipants.get(Binder.getCallingUid());
1618 } else {
1619 // a caller with full permission can ask to back up any participating app
1620 // !!! TODO: allow data-clear of ANY app?
1621 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1622 apps = new HashSet<ApplicationInfo>();
1623 int N = mBackupParticipants.size();
1624 for (int i = 0; i < N; i++) {
1625 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1626 if (s != null) {
1627 apps.addAll(s);
1628 }
1629 }
1630 }
1631
1632 // now find the given package in the set of candidate apps
1633 for (ApplicationInfo app : apps) {
1634 if (app.packageName.equals(packageName)) {
1635 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1636 // found it; fire off the clear request
1637 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001638 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001639 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001640 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1641 new ClearParams(getTransport(mCurrentTransport), info));
1642 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001643 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001644 }
1645 break;
1646 }
1647 }
1648 }
1649
Christopher Tateace7f092009-06-15 18:07:25 -07001650 // Run a backup pass immediately for any applications that have declared
1651 // that they have pending updates.
1652 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001654
Christopher Tateace7f092009-06-15 18:07:25 -07001655 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001656 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001657 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001658 mRunBackupIntent.send();
1659 } catch (PendingIntent.CanceledException e) {
1660 // should never happen
1661 Log.e(TAG, "run-backup intent cancelled!");
1662 }
Christopher Tate46758122009-05-06 11:22:00 -07001663 }
1664 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001665
Christopher Tate8031a3d2009-07-06 16:36:05 -07001666 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001667 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1669 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001670
1671 boolean wasEnabled = mEnabled;
1672 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001673 Settings.Secure.putInt(mContext.getContentResolver(),
1674 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001675 mEnabled = enable;
1676 }
1677
Christopher Tate49401dd2009-07-01 12:34:29 -07001678 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001679 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001680 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001681 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001682 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001683 // No longer enabled, so stop running backups
1684 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001685 }
1686 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001687 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001688
Christopher Tate8031a3d2009-07-06 16:36:05 -07001689 // Mark the backup service as having been provisioned
1690 public void setBackupProvisioned(boolean available) {
1691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1692 "setBackupProvisioned");
1693
1694 boolean wasProvisioned = mProvisioned;
1695 synchronized (this) {
1696 Settings.Secure.putInt(mContext.getContentResolver(),
1697 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1698 mProvisioned = available;
1699 }
1700
1701 synchronized (mQueueLock) {
1702 if (available && !wasProvisioned && mEnabled) {
1703 // we're now good to go, so start the backup alarms
1704 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1705 } else if (!available) {
1706 // No longer enabled, so stop running backups
1707 Log.w(TAG, "Backup service no longer provisioned");
1708 mAlarmManager.cancel(mRunBackupIntent);
1709 }
1710 }
1711 }
1712
1713 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1714 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1715 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1716 BACKUP_INTERVAL, mRunBackupIntent);
1717 }
1718
Christopher Tate6ef58a12009-06-29 14:56:28 -07001719 // Report whether the backup mechanism is currently enabled
1720 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001722 return mEnabled; // no need to synchronize just to read it
1723 }
1724
Christopher Tate91717492009-06-26 21:07:13 -07001725 // Report the name of the currently active transport
1726 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001727 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001728 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001729 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001730 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001731 }
1732
Christopher Tate91717492009-06-26 21:07:13 -07001733 // Report all known, available backup transports
1734 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001735 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001736
Christopher Tate91717492009-06-26 21:07:13 -07001737 String[] list = null;
1738 ArrayList<String> known = new ArrayList<String>();
1739 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1740 if (entry.getValue() != null) {
1741 known.add(entry.getKey());
1742 }
1743 }
1744
1745 if (known.size() > 0) {
1746 list = new String[known.size()];
1747 known.toArray(list);
1748 }
1749 return list;
1750 }
1751
1752 // Select which transport to use for the next backup operation. If the given
1753 // name is not one of the available transports, no action is taken and the method
1754 // returns null.
1755 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001757
1758 synchronized (mTransports) {
1759 String prevTransport = null;
1760 if (mTransports.get(transport) != null) {
1761 prevTransport = mCurrentTransport;
1762 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001763 Settings.Secure.putString(mContext.getContentResolver(),
1764 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001765 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1766 + " returning " + prevTransport);
1767 } else {
1768 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1769 }
1770 return prevTransport;
1771 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001772 }
1773
1774 // Callback: a requested backup agent has been instantiated. This should only
1775 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001776 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001777 synchronized(mAgentConnectLock) {
1778 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1779 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1780 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1781 mConnectedAgent = agent;
1782 mConnecting = false;
1783 } else {
1784 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1785 + " claiming agent connected");
1786 }
1787 mAgentConnectLock.notifyAll();
1788 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001789 }
1790
1791 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1792 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001793 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001794 public void agentDisconnected(String packageName) {
1795 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001796 synchronized(mAgentConnectLock) {
1797 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1798 mConnectedAgent = null;
1799 mConnecting = false;
1800 } else {
1801 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1802 + " claiming agent disconnected");
1803 }
1804 mAgentConnectLock.notifyAll();
1805 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001806 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001807
Christopher Tate8c850b72009-06-07 19:33:20 -07001808 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001809 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001811
1812 synchronized(this) {
1813 if (mActiveRestoreSession != null) {
1814 Log.d(TAG, "Restore session requested but one already active");
1815 return null;
1816 }
Christopher Tate91717492009-06-26 21:07:13 -07001817 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001818 }
1819 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001820 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001821
Christopher Tate9b3905c2009-06-08 15:24:01 -07001822 // ----- Restore session -----
1823
1824 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001825 private static final String TAG = "RestoreSession";
1826
Christopher Tate9b3905c2009-06-08 15:24:01 -07001827 private IBackupTransport mRestoreTransport = null;
1828 RestoreSet[] mRestoreSets = null;
1829
Christopher Tate91717492009-06-26 21:07:13 -07001830 RestoreSession(String transport) {
1831 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001832 }
1833
1834 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07001835 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04001836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001837 "getAvailableRestoreSets");
1838
Christopher Tatef68eb502009-06-16 11:02:01 -07001839 try {
Christopher Tate43383042009-07-13 15:17:13 -07001840 if (mRestoreTransport == null) {
1841 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07001842 return null;
1843 }
1844 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001845 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001846 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001847 }
1848 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07001849 } catch (Exception e) {
1850 Log.e(TAG, "Error in getAvailableRestoreSets", e);
1851 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001852 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001853 }
1854
Dan Egnor0084da52009-07-29 12:57:16 -07001855 public synchronized int performRestore(long token, IRestoreObserver observer) {
1856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1857 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001858
Christopher Tatef2c321a2009-08-10 15:43:36 -07001859 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
1860 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001861
Dan Egnor0084da52009-07-29 12:57:16 -07001862 if (mRestoreTransport == null || mRestoreSets == null) {
1863 Log.e(TAG, "Ignoring performRestore() with no restore set");
1864 return -1;
1865 }
1866
1867 for (int i = 0; i < mRestoreSets.length; i++) {
1868 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001869 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07001870 mWakelock.acquire();
1871 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1872 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
1873 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001874 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07001875 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001876 }
1877 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07001878
1879 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07001880 return -1;
1881 }
1882
Dan Egnor0084da52009-07-29 12:57:16 -07001883 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04001884 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001885 "endRestoreSession");
1886
Dan Egnor0084da52009-07-29 12:57:16 -07001887 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001888
Dan Egnor0084da52009-07-29 12:57:16 -07001889 synchronized (this) {
1890 try {
1891 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
1892 } catch (Exception e) {
1893 Log.e(TAG, "Error in finishRestore", e);
1894 } finally {
1895 mRestoreTransport = null;
1896 }
1897 }
1898
1899 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07001900 if (BackupManagerService.this.mActiveRestoreSession == this) {
1901 BackupManagerService.this.mActiveRestoreSession = null;
1902 } else {
1903 Log.e(TAG, "ending non-current restore session");
1904 }
1905 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001906 }
1907 }
1908
Christopher Tate043dadc2009-06-02 16:11:00 -07001909
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001910 @Override
1911 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1912 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001913 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1914 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001915 pw.println("Available transports:");
1916 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001917 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1918 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001919 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001920 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001921 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001922 for (int i=0; i<N; i++) {
1923 int uid = mBackupParticipants.keyAt(i);
1924 pw.print(" uid: ");
1925 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001926 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1927 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001928 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001929 }
1930 }
Christopher Tate73e02522009-07-15 14:18:26 -07001931 pw.println("Ever backed up: " + mEverStoredApps.size());
1932 for (String pkg : mEverStoredApps) {
1933 pw.println(" " + pkg);
1934 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001935 pw.println("Pending: " + mPendingBackups.size());
1936 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001937 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001938 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001939 }
1940 }
Christopher Tate487529a2009-04-29 14:03:25 -07001941}