blob: 1dc51c8cc72b647e665f762a67e580a1e8e1a94b [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());
Dan Egnor01445162009-09-21 17:04:05 -0700923 int status = BackupConstants.TRANSPORT_OK;
924
925 // If we haven't stored anything yet, we need to do an init operation.
926 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
927 status = mTransport.initializeDevice();
928 }
Dan Egnorbb9001c2009-07-27 12:20:13 -0700929
930 // The package manager doesn't have a proper <application> etc, but since
931 // it's running here in the system process we can just set up its agent
932 // directly and use a synthetic BackupRequest. We always run this pass
933 // because it's cheap and this way we guarantee that we don't get out of
934 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -0700935 if (status == BackupConstants.TRANSPORT_OK) {
936 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
937 mPackageManager, allAgentPackages());
938 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
939 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
940 status = processOneBackup(pmRequest,
941 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
942 }
Christopher Tate90967f42009-09-20 15:28:33 -0700943
Dan Egnor01445162009-09-21 17:04:05 -0700944 if (status == BackupConstants.TRANSPORT_OK) {
945 // Now run all the backups in our queue
946 status = doQueuedBackups(mTransport);
947 }
948
949 if (status == BackupConstants.TRANSPORT_OK) {
950 // Tell the transport to finish everything it has buffered
951 status = mTransport.finishBackup();
952 if (status == BackupConstants.TRANSPORT_OK) {
953 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
954 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
955 } else {
956 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
957 Log.e(TAG, "Transport error in finishBackup()");
958 }
959 }
960
961 // When we succeed at everything, we can remove the journal
962 if (status == BackupConstants.TRANSPORT_OK && !mJournal.delete()) {
963 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
964 }
965
966 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -0700967 // The backend reports that our dataset has been wiped. We need to
968 // reset all of our bookkeeping and instead run a new backup pass for
969 // everything.
970 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
971 resetBackupState(mStateDir);
972 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -0700973 }
974 } catch (Exception e) {
975 Log.e(TAG, "Error in backup thread", e);
976 } finally {
977 // Only once we're entirely finished do we release the wakelock
978 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -0700979 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700980 }
981
Dan Egnor01445162009-09-21 17:04:05 -0700982 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700983 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700984 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700985
Christopher Tate0749dcd2009-08-13 15:13:03 -0700986 // Don't run backup, even if requested, if the target app does not have
987 // the requisite permission
988 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
989 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
990 Log.w(TAG, "Skipping backup of unprivileged package "
991 + request.appInfo.packageName);
992 continue;
993 }
994
Christopher Tate043dadc2009-06-02 16:11:00 -0700995 IBackupAgent agent = null;
996 int mode = (request.fullBackup)
997 ? IApplicationThread.BACKUP_MODE_FULL
998 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
999 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001000 agent = bindToAgentSynchronous(request.appInfo, mode);
1001 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001002 int result = processOneBackup(request, agent, transport);
1003 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001004 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001005 } catch (SecurityException ex) {
1006 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001007 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001008 } finally {
1009 try { // unbind even on timeout, just in case
1010 mActivityManager.unbindBackupAgent(request.appInfo);
1011 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001012 }
1013 }
Dan Egnor01445162009-09-21 17:04:05 -07001014
1015 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001016 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001017
Dan Egnor01445162009-09-21 17:04:05 -07001018 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1019 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001020 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001021 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001022
Dan Egnorbb9001c2009-07-27 12:20:13 -07001023 File savedStateName = new File(mStateDir, packageName);
1024 File backupDataName = new File(mDataDir, packageName + ".data");
1025 File newStateName = new File(mStateDir, packageName + ".new");
1026
1027 ParcelFileDescriptor savedState = null;
1028 ParcelFileDescriptor backupData = null;
1029 ParcelFileDescriptor newState = null;
1030
1031 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001032 try {
1033 // Look up the package info & signatures. This is first so that if it
1034 // throws an exception, there's no file setup yet that would need to
1035 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001036 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1037 // The metadata 'package' is synthetic
1038 packInfo = new PackageInfo();
1039 packInfo.packageName = packageName;
1040 } else {
1041 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001042 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001043 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001044
Christopher Tatec7b31e32009-06-10 15:49:30 -07001045 // In a full backup, we pass a null ParcelFileDescriptor as
1046 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001047 if (!request.fullBackup) {
1048 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001049 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001050 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1051 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001052
Dan Egnorbb9001c2009-07-27 12:20:13 -07001053 backupData = ParcelFileDescriptor.open(backupDataName,
1054 ParcelFileDescriptor.MODE_READ_WRITE |
1055 ParcelFileDescriptor.MODE_CREATE |
1056 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001057
Dan Egnorbb9001c2009-07-27 12:20:13 -07001058 newState = ParcelFileDescriptor.open(newStateName,
1059 ParcelFileDescriptor.MODE_READ_WRITE |
1060 ParcelFileDescriptor.MODE_CREATE |
1061 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001062
1063 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001064 agent.doBackup(savedState, backupData, newState);
1065 logBackupComplete(packageName);
1066 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001067 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001068 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001069 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1070 backupDataName.delete();
1071 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001072 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001073 } finally {
1074 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1075 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1076 try { if (newState != null) newState.close(); } catch (IOException e) {}
1077 savedState = backupData = newState = null;
1078 }
1079
1080 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001081 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001082 try {
1083 int size = (int) backupDataName.length();
1084 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001085 if (result == BackupConstants.TRANSPORT_OK) {
1086 backupData = ParcelFileDescriptor.open(backupDataName,
1087 ParcelFileDescriptor.MODE_READ_ONLY);
1088 result = transport.performBackup(packInfo, backupData);
1089 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001090
Dan Egnor83861e72009-09-17 16:17:55 -07001091 // TODO - We call finishBackup() for each application backed up, because
1092 // we need to know now whether it succeeded or failed. Instead, we should
1093 // hold off on finishBackup() until the end, which implies holding off on
1094 // renaming *all* the output state files (see below) until that happens.
1095
Dan Egnor01445162009-09-21 17:04:05 -07001096 if (result == BackupConstants.TRANSPORT_OK) {
1097 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001098 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001099 } else {
1100 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1101 }
1102
1103 // After successful transport, delete the now-stale data
1104 // and juggle the files so that next time we supply the agent
1105 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001106 if (result == BackupConstants.TRANSPORT_OK) {
1107 backupDataName.delete();
1108 newStateName.renameTo(savedStateName);
1109 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1110 } else {
1111 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1112 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001113 } catch (Exception e) {
1114 Log.e(TAG, "Transport error backing up " + packageName, e);
1115 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001116 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001117 } finally {
1118 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001119 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001120
Dan Egnor01445162009-09-21 17:04:05 -07001121 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001122 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001123 }
1124
Christopher Tatedf01dea2009-06-09 20:45:02 -07001125
1126 // ----- Restore handling -----
1127
Christopher Tateabce4e82009-06-18 18:35:32 -07001128 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001129 // Allow unsigned apps, but not signed on one device and unsigned on the other
1130 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001131 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1132 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001133 if ((storedSigs == null || storedSigs.length == 0)
1134 && (deviceSigs == null || deviceSigs.length == 0)) {
1135 return true;
1136 }
1137 if (storedSigs == null || deviceSigs == null) {
1138 return false;
1139 }
1140
Christopher Tateabce4e82009-06-18 18:35:32 -07001141 // !!! TODO: this demands that every stored signature match one
1142 // that is present on device, and does not demand the converse.
1143 // Is this this right policy?
1144 int nStored = storedSigs.length;
1145 int nDevice = deviceSigs.length;
1146
1147 for (int i=0; i < nStored; i++) {
1148 boolean match = false;
1149 for (int j=0; j < nDevice; j++) {
1150 if (storedSigs[i].equals(deviceSigs[j])) {
1151 match = true;
1152 break;
1153 }
1154 }
1155 if (!match) {
1156 return false;
1157 }
1158 }
1159 return true;
1160 }
1161
Christopher Tatedf01dea2009-06-09 20:45:02 -07001162 class PerformRestoreThread extends Thread {
1163 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001164 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001165 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001166 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001167
Christopher Tate5cbbf562009-06-22 16:44:51 -07001168 class RestoreRequest {
1169 public PackageInfo app;
1170 public int storedAppVersion;
1171
1172 RestoreRequest(PackageInfo _app, int _version) {
1173 app = _app;
1174 storedAppVersion = _version;
1175 }
1176 }
1177
Christopher Tate7d562ec2009-06-25 18:03:43 -07001178 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001179 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001180 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001181 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001182 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001183 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001184
1185 try {
1186 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1187 } catch (RemoteException e) {
1188 // can't happen; the transport is local
1189 }
1190 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001191 }
1192
1193 @Override
1194 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001195 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001196 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001197 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001198 /**
1199 * Restore sequence:
1200 *
Dan Egnorefe52642009-06-24 00:16:33 -07001201 * 1. get the restore set description for our identity
1202 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001203 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001204 * 3. for each app in the restore queue:
1205 * 3.a. clear the app data
1206 * 3.b. get the restore data for the app from the transport
1207 * 3.c. launch the backup agent for the app
1208 * 3.d. agent.doRestore() with the data from the server
1209 * 3.e. unbind the agent [and kill the app?]
1210 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001211 *
1212 * On errors, we try our best to recover and move on to the next
1213 * application, but if necessary we abort the whole operation --
1214 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001215 */
1216
Christopher Tate7d562ec2009-06-25 18:03:43 -07001217 int error = -1; // assume error
1218
Dan Egnorefe52642009-06-24 00:16:33 -07001219 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001220 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001221 // TODO: Log this before getAvailableRestoreSets, somehow
1222 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName());
Christopher Tateabce4e82009-06-18 18:35:32 -07001223
Dan Egnorefe52642009-06-24 00:16:33 -07001224 // Get the list of all packages which have backup enabled.
1225 // (Include the Package Manager metadata pseudo-package first.)
1226 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1227 PackageInfo omPackage = new PackageInfo();
1228 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1229 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001230
Dan Egnorefe52642009-06-24 00:16:33 -07001231 List<PackageInfo> agentPackages = allAgentPackages();
1232 restorePackages.addAll(agentPackages);
1233
Christopher Tate7d562ec2009-06-25 18:03:43 -07001234 // let the observer know that we're running
1235 if (mObserver != null) {
1236 try {
1237 // !!! TODO: get an actual count from the transport after
1238 // its startRestore() runs?
1239 mObserver.restoreStarting(restorePackages.size());
1240 } catch (RemoteException e) {
1241 Log.d(TAG, "Restore observer died at restoreStarting");
1242 mObserver = null;
1243 }
1244 }
1245
Dan Egnor01445162009-09-21 17:04:05 -07001246 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1247 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001248 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001249 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001250 return;
1251 }
1252
1253 String packageName = mTransport.nextRestorePackage();
1254 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001255 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001256 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001257 return;
1258 } else if (packageName.equals("")) {
1259 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001260 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1261 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001262 return;
1263 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1264 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1265 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001266 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1267 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001268 return;
1269 }
1270
1271 // Pull the Package Manager metadata from the restore set first
1272 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1273 mPackageManager, agentPackages);
1274 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1275
Christopher Tate8c032472009-07-02 14:28:47 -07001276 // Verify that the backup set includes metadata. If not, we can't do
1277 // signature/version verification etc, so we simply do not proceed with
1278 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001279 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001280 Log.e(TAG, "No restore metadata available, so not restoring settings");
1281 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1282 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001283 return;
1284 }
1285
Christopher Tate7d562ec2009-06-25 18:03:43 -07001286 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001287 for (;;) {
1288 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001289
Dan Egnorefe52642009-06-24 00:16:33 -07001290 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001291 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001292 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001293 return;
1294 } else if (packageName.equals("")) {
1295 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001296 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001297
Christopher Tate7d562ec2009-06-25 18:03:43 -07001298 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001299 try {
1300 mObserver.onUpdate(count);
1301 } catch (RemoteException e) {
1302 Log.d(TAG, "Restore observer died in onUpdate");
1303 mObserver = null;
1304 }
1305 }
1306
Dan Egnorefe52642009-06-24 00:16:33 -07001307 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1308 if (metaInfo == null) {
1309 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001310 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1311 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001312 continue;
1313 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001314
Dan Egnorbb9001c2009-07-27 12:20:13 -07001315 PackageInfo packageInfo;
1316 try {
1317 int flags = PackageManager.GET_SIGNATURES;
1318 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1319 } catch (NameNotFoundException e) {
1320 Log.e(TAG, "Invalid package restoring data", e);
1321 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1322 "Package missing on device");
1323 continue;
1324 }
1325
Dan Egnorefe52642009-06-24 00:16:33 -07001326 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001327 String message = "Version " + metaInfo.versionCode
1328 + " > installed version " + packageInfo.versionCode;
1329 Log.w(TAG, "Package " + packageName + ": " + message);
1330 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
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 (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1335 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001336 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1337 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001338 continue;
1339 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001340
Dan Egnorefe52642009-06-24 00:16:33 -07001341 if (DEBUG) Log.v(TAG, "Package " + packageName
1342 + " restore version [" + metaInfo.versionCode
1343 + "] is compatible with installed version ["
1344 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001345
Christopher Tate5e1ab332009-09-01 20:32:49 -07001346 // Now perform the actual restore: first clear the app's data
1347 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001348 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001349
1350 // Then set up and bind the agent (with a restricted Application object
1351 // unless the application says otherwise)
1352 boolean useRealApp = (packageInfo.applicationInfo.flags
1353 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1354 if (DEBUG && useRealApp) {
1355 Log.v(TAG, "agent requires real Application subclass for restore");
1356 }
Dan Egnorefe52642009-06-24 00:16:33 -07001357 IBackupAgent agent = bindToAgentSynchronous(
1358 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001359 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1360 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001361 if (agent == null) {
1362 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001363 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1364 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001365 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001366 }
1367
Christopher Tate5e1ab332009-09-01 20:32:49 -07001368 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001369 try {
1370 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001371 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001372 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001373 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001374 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001375
1376 // The agent was probably running with a stub Application object,
1377 // which isn't a valid run mode for the main app logic. Shut
1378 // down the app so that next time it's launched, it gets the
1379 // usual full initialization.
1380 if ((packageInfo.applicationInfo.flags
1381 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1382 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1383 + packageInfo.applicationInfo.processName);
1384 mActivityManager.killApplicationProcess(
1385 packageInfo.applicationInfo.processName,
1386 packageInfo.applicationInfo.uid);
1387 }
Dan Egnorefe52642009-06-24 00:16:33 -07001388 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001389 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001390
1391 // if we get this far, report success to the observer
1392 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001393 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1394 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1395 } catch (Exception e) {
1396 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001397 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001398 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1399
Dan Egnorefe52642009-06-24 00:16:33 -07001400 try {
1401 mTransport.finishRestore();
1402 } catch (RemoteException e) {
1403 Log.e(TAG, "Error finishing restore", e);
1404 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001405
1406 if (mObserver != null) {
1407 try {
1408 mObserver.restoreFinished(error);
1409 } catch (RemoteException e) {
1410 Log.d(TAG, "Restore observer died at restoreFinished");
1411 }
1412 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001413
1414 // done; we can finally release the wakelock
1415 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001416 }
1417 }
1418
Dan Egnorefe52642009-06-24 00:16:33 -07001419 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1420 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001421 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001422 final String packageName = app.packageName;
1423
Dan Egnorbb9001c2009-07-27 12:20:13 -07001424 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001425
Christopher Tate0749dcd2009-08-13 15:13:03 -07001426 // Don't restore to unprivileged packages
1427 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1428 packageName) != PackageManager.PERMISSION_GRANTED) {
1429 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1430 }
1431
Christopher Tatec7b31e32009-06-10 15:49:30 -07001432 // !!! TODO: get the dirs from the transport
1433 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434 File newStateName = new File(mStateDir, packageName + ".new");
1435 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001436
Dan Egnorbb9001c2009-07-27 12:20:13 -07001437 ParcelFileDescriptor backupData = null;
1438 ParcelFileDescriptor newState = null;
1439
1440 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001441 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001442 backupData = ParcelFileDescriptor.open(backupDataName,
1443 ParcelFileDescriptor.MODE_READ_WRITE |
1444 ParcelFileDescriptor.MODE_CREATE |
1445 ParcelFileDescriptor.MODE_TRUNCATE);
1446
Dan Egnor01445162009-09-21 17:04:05 -07001447 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001448 Log.e(TAG, "Error getting restore data for " + packageName);
1449 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1450 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001451 }
1452
1453 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001454 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001455 backupData = ParcelFileDescriptor.open(backupDataName,
1456 ParcelFileDescriptor.MODE_READ_ONLY);
1457
Dan Egnorbb9001c2009-07-27 12:20:13 -07001458 newState = ParcelFileDescriptor.open(newStateName,
1459 ParcelFileDescriptor.MODE_READ_WRITE |
1460 ParcelFileDescriptor.MODE_CREATE |
1461 ParcelFileDescriptor.MODE_TRUNCATE);
1462
1463 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001464
1465 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001466 //
1467 // !!! TODO: the restored data should be migrated on the server
1468 // side into the current dataset. In that case the new state file
1469 // we just created would reflect the data already extant in the
1470 // backend, so there'd be nothing more to do. Until that happens,
1471 // however, we need to make sure that we record the data to the
1472 // current backend dataset. (Yes, this means shipping the data over
1473 // the wire in both directions. That's bad, but consistency comes
1474 // first, then efficiency.) Once we introduce server-side data
1475 // migration to the newly-restored device's dataset, we will change
1476 // the following from a discard of the newly-written state to the
1477 // "correct" operation of renaming into the canonical state blob.
1478 newStateName.delete(); // TODO: remove; see above comment
1479 //newStateName.renameTo(savedStateName); // TODO: replace with this
1480
Dan Egnorbb9001c2009-07-27 12:20:13 -07001481 int size = (int) backupDataName.length();
1482 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001483 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001484 Log.e(TAG, "Error restoring data for " + packageName, e);
1485 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1486
Christopher Tate96733042009-07-20 14:49:13 -07001487 // If the agent fails restore, it might have put the app's data
1488 // into an incoherent state. For consistency we wipe its data
1489 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001490 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001491 } finally {
1492 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001493 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1494 try { if (newState != null) newState.close(); } catch (IOException e) {}
1495 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001496 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001497 }
1498 }
1499
Christopher Tateee0e78a2009-07-02 11:17:03 -07001500 class PerformClearThread extends Thread {
1501 IBackupTransport mTransport;
1502 PackageInfo mPackage;
1503
1504 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1505 mTransport = transport;
1506 mPackage = packageInfo;
1507 }
1508
1509 @Override
1510 public void run() {
1511 try {
1512 // Clear the on-device backup state to ensure a full backup next time
1513 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1514 File stateFile = new File(stateDir, mPackage.packageName);
1515 stateFile.delete();
1516
1517 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001518 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001519 mTransport.clearBackupData(mPackage);
1520 } catch (RemoteException e) {
1521 // can't happen; the transport is local
1522 } finally {
1523 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001524 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001525 mTransport.finishBackup();
1526 } catch (RemoteException e) {
1527 // can't happen; the transport is local
1528 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001529
1530 // Last but not least, release the cpu
1531 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001532 }
1533 }
1534 }
1535
Christopher Tatedf01dea2009-06-09 20:45:02 -07001536
Christopher Tate487529a2009-04-29 14:03:25 -07001537 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001538
Christopher Tatea8bf8152009-04-30 11:36:21 -07001539 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001540 // Record that we need a backup pass for the caller. Since multiple callers
1541 // may share a uid, we need to note all candidates within that uid and schedule
1542 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001543 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001544
Christopher Tate63d27002009-06-16 17:16:42 -07001545 // If the caller does not hold the BACKUP permission, it can only request a
1546 // backup of its own data.
1547 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001548 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001549 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1550 targets = mBackupParticipants.get(Binder.getCallingUid());
1551 } else {
1552 // a caller with full permission can ask to back up any participating app
1553 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001554 targets = new HashSet<ApplicationInfo>();
1555 int N = mBackupParticipants.size();
1556 for (int i = 0; i < N; i++) {
1557 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1558 if (s != null) {
1559 targets.addAll(s);
1560 }
1561 }
1562 }
Christopher Tate487529a2009-04-29 14:03:25 -07001563 if (targets != null) {
1564 synchronized (mQueueLock) {
1565 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001566 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001567 // validate the caller-supplied package name against the known set of
1568 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001569 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001570 // Add the caller to the set of pending backups. If there is
1571 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001572 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001573 if (mPendingBackups.put(app, req) == null) {
1574 // Journal this request in case of crash. The put()
1575 // operation returned null when this package was not already
1576 // in the set; we want to avoid touching the disk redundantly.
1577 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001578
Christopher Tate22b60d82009-07-07 16:36:02 -07001579 if (DEBUG) {
1580 int numKeys = mPendingBackups.size();
1581 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1582 for (BackupRequest b : mPendingBackups.values()) {
1583 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1584 }
1585 }
1586 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001587 }
1588 }
Christopher Tate487529a2009-04-29 14:03:25 -07001589 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001590 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001591 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1592 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001593 }
1594 }
Christopher Tate46758122009-05-06 11:22:00 -07001595
Christopher Tatecde87f42009-06-12 12:55:53 -07001596 private void writeToJournalLocked(String str) {
1597 if (mJournalStream != null) {
1598 try {
1599 mJournalStream.writeUTF(str);
1600 } catch (IOException e) {
1601 Log.e(TAG, "Error writing to backup journal");
1602 mJournalStream = null;
1603 mJournal = null;
1604 }
1605 }
1606 }
1607
Christopher Tateee0e78a2009-07-02 11:17:03 -07001608 // Clear the given package's backup data from the current transport
1609 public void clearBackupData(String packageName) {
1610 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1611 PackageInfo info;
1612 try {
1613 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1614 } catch (NameNotFoundException e) {
1615 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1616 return;
1617 }
1618
1619 // If the caller does not hold the BACKUP permission, it can only request a
1620 // wipe of its own backed-up data.
1621 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001622 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001623 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1624 apps = mBackupParticipants.get(Binder.getCallingUid());
1625 } else {
1626 // a caller with full permission can ask to back up any participating app
1627 // !!! TODO: allow data-clear of ANY app?
1628 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1629 apps = new HashSet<ApplicationInfo>();
1630 int N = mBackupParticipants.size();
1631 for (int i = 0; i < N; i++) {
1632 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1633 if (s != null) {
1634 apps.addAll(s);
1635 }
1636 }
1637 }
1638
1639 // now find the given package in the set of candidate apps
1640 for (ApplicationInfo app : apps) {
1641 if (app.packageName.equals(packageName)) {
1642 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1643 // found it; fire off the clear request
1644 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001645 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001646 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001647 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1648 new ClearParams(getTransport(mCurrentTransport), info));
1649 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001650 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001651 }
1652 break;
1653 }
1654 }
1655 }
1656
Christopher Tateace7f092009-06-15 18:07:25 -07001657 // Run a backup pass immediately for any applications that have declared
1658 // that they have pending updates.
1659 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001661
Christopher Tateace7f092009-06-15 18:07:25 -07001662 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001663 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001664 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001665 mRunBackupIntent.send();
1666 } catch (PendingIntent.CanceledException e) {
1667 // should never happen
1668 Log.e(TAG, "run-backup intent cancelled!");
1669 }
Christopher Tate46758122009-05-06 11:22:00 -07001670 }
1671 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001672
Christopher Tate8031a3d2009-07-06 16:36:05 -07001673 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001674 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1676 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001677
1678 boolean wasEnabled = mEnabled;
1679 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001680 Settings.Secure.putInt(mContext.getContentResolver(),
1681 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001682 mEnabled = enable;
1683 }
1684
Christopher Tate49401dd2009-07-01 12:34:29 -07001685 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001686 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001687 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001688 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001689 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001690 // No longer enabled, so stop running backups
1691 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001692 }
1693 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001694 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001695
Christopher Tate8031a3d2009-07-06 16:36:05 -07001696 // Mark the backup service as having been provisioned
1697 public void setBackupProvisioned(boolean available) {
1698 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1699 "setBackupProvisioned");
1700
1701 boolean wasProvisioned = mProvisioned;
1702 synchronized (this) {
1703 Settings.Secure.putInt(mContext.getContentResolver(),
1704 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1705 mProvisioned = available;
1706 }
1707
1708 synchronized (mQueueLock) {
1709 if (available && !wasProvisioned && mEnabled) {
1710 // we're now good to go, so start the backup alarms
1711 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1712 } else if (!available) {
1713 // No longer enabled, so stop running backups
1714 Log.w(TAG, "Backup service no longer provisioned");
1715 mAlarmManager.cancel(mRunBackupIntent);
1716 }
1717 }
1718 }
1719
1720 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1721 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1722 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1723 BACKUP_INTERVAL, mRunBackupIntent);
1724 }
1725
Christopher Tate6ef58a12009-06-29 14:56:28 -07001726 // Report whether the backup mechanism is currently enabled
1727 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001729 return mEnabled; // no need to synchronize just to read it
1730 }
1731
Christopher Tate91717492009-06-26 21:07:13 -07001732 // Report the name of the currently active transport
1733 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001734 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001735 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001736 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001737 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001738 }
1739
Christopher Tate91717492009-06-26 21:07:13 -07001740 // Report all known, available backup transports
1741 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001743
Christopher Tate91717492009-06-26 21:07:13 -07001744 String[] list = null;
1745 ArrayList<String> known = new ArrayList<String>();
1746 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1747 if (entry.getValue() != null) {
1748 known.add(entry.getKey());
1749 }
1750 }
1751
1752 if (known.size() > 0) {
1753 list = new String[known.size()];
1754 known.toArray(list);
1755 }
1756 return list;
1757 }
1758
1759 // Select which transport to use for the next backup operation. If the given
1760 // name is not one of the available transports, no action is taken and the method
1761 // returns null.
1762 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001764
1765 synchronized (mTransports) {
1766 String prevTransport = null;
1767 if (mTransports.get(transport) != null) {
1768 prevTransport = mCurrentTransport;
1769 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001770 Settings.Secure.putString(mContext.getContentResolver(),
1771 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001772 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1773 + " returning " + prevTransport);
1774 } else {
1775 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1776 }
1777 return prevTransport;
1778 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001779 }
1780
1781 // Callback: a requested backup agent has been instantiated. This should only
1782 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001783 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001784 synchronized(mAgentConnectLock) {
1785 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1786 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1787 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1788 mConnectedAgent = agent;
1789 mConnecting = false;
1790 } else {
1791 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1792 + " claiming agent connected");
1793 }
1794 mAgentConnectLock.notifyAll();
1795 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001796 }
1797
1798 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1799 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001800 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001801 public void agentDisconnected(String packageName) {
1802 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001803 synchronized(mAgentConnectLock) {
1804 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1805 mConnectedAgent = null;
1806 mConnecting = false;
1807 } else {
1808 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1809 + " claiming agent disconnected");
1810 }
1811 mAgentConnectLock.notifyAll();
1812 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001813 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001814
Christopher Tate8c850b72009-06-07 19:33:20 -07001815 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001816 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001817 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001818
1819 synchronized(this) {
1820 if (mActiveRestoreSession != null) {
1821 Log.d(TAG, "Restore session requested but one already active");
1822 return null;
1823 }
Christopher Tate91717492009-06-26 21:07:13 -07001824 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001825 }
1826 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001827 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001828
Christopher Tate9b3905c2009-06-08 15:24:01 -07001829 // ----- Restore session -----
1830
1831 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001832 private static final String TAG = "RestoreSession";
1833
Christopher Tate9b3905c2009-06-08 15:24:01 -07001834 private IBackupTransport mRestoreTransport = null;
1835 RestoreSet[] mRestoreSets = null;
1836
Christopher Tate91717492009-06-26 21:07:13 -07001837 RestoreSession(String transport) {
1838 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001839 }
1840
1841 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07001842 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04001843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001844 "getAvailableRestoreSets");
1845
Christopher Tatef68eb502009-06-16 11:02:01 -07001846 try {
Christopher Tate43383042009-07-13 15:17:13 -07001847 if (mRestoreTransport == null) {
1848 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07001849 return null;
1850 }
1851 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001852 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001854 }
1855 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07001856 } catch (Exception e) {
1857 Log.e(TAG, "Error in getAvailableRestoreSets", e);
1858 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001859 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001860 }
1861
Dan Egnor0084da52009-07-29 12:57:16 -07001862 public synchronized int performRestore(long token, IRestoreObserver observer) {
1863 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1864 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001865
Christopher Tatef2c321a2009-08-10 15:43:36 -07001866 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
1867 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001868
Dan Egnor0084da52009-07-29 12:57:16 -07001869 if (mRestoreTransport == null || mRestoreSets == null) {
1870 Log.e(TAG, "Ignoring performRestore() with no restore set");
1871 return -1;
1872 }
1873
1874 for (int i = 0; i < mRestoreSets.length; i++) {
1875 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001876 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07001877 mWakelock.acquire();
1878 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1879 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
1880 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001881 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07001882 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001883 }
1884 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07001885
1886 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07001887 return -1;
1888 }
1889
Dan Egnor0084da52009-07-29 12:57:16 -07001890 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04001891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001892 "endRestoreSession");
1893
Dan Egnor0084da52009-07-29 12:57:16 -07001894 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001895
Dan Egnor0084da52009-07-29 12:57:16 -07001896 synchronized (this) {
1897 try {
1898 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
1899 } catch (Exception e) {
1900 Log.e(TAG, "Error in finishRestore", e);
1901 } finally {
1902 mRestoreTransport = null;
1903 }
1904 }
1905
1906 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07001907 if (BackupManagerService.this.mActiveRestoreSession == this) {
1908 BackupManagerService.this.mActiveRestoreSession = null;
1909 } else {
1910 Log.e(TAG, "ending non-current restore session");
1911 }
1912 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001913 }
1914 }
1915
Christopher Tate043dadc2009-06-02 16:11:00 -07001916
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001917 @Override
1918 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1919 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001920 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1921 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001922 pw.println("Available transports:");
1923 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001924 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1925 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001926 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001927 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001928 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001929 for (int i=0; i<N; i++) {
1930 int uid = mBackupParticipants.keyAt(i);
1931 pw.print(" uid: ");
1932 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001933 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1934 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001935 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001936 }
1937 }
Christopher Tate73e02522009-07-15 14:18:26 -07001938 pw.println("Ever backed up: " + mEverStoredApps.size());
1939 for (String pkg : mEverStoredApps) {
1940 pw.println(" " + pkg);
1941 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001942 pw.println("Pending: " + mPendingBackups.size());
1943 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001944 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001945 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001946 }
1947 }
Christopher Tate487529a2009-04-29 14:03:25 -07001948}