blob: 854a6f9ca024e9a156ffccba56218c5cf07c0d95 [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 Tate9bbc21a2009-06-10 20:23:25 -070060import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tate6785dd82009-06-18 15:58:25 -070063import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070069import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070070import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070071import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070072import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040073import java.util.ArrayList;
74import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070075import java.util.HashSet;
76import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070077import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070078
79class BackupManagerService extends IBackupManager.Stub {
80 private static final String TAG = "BackupManagerService";
81 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070082
Christopher Tate49401dd2009-07-01 12:34:29 -070083 // How often we perform a backup pass. Privileged external callers can
84 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070085 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070086
Christopher Tate8031a3d2009-07-06 16:36:05 -070087 // The amount of time between the initial provisioning of the device and
88 // the first backup pass.
89 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
90
Christopher Tateb6787f22009-07-02 17:40:45 -070091 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070092 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070093 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070094 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070095 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070096
Dan Egnorbb9001c2009-07-27 12:20:13 -070097 // Event tags -- see system/core/logcat/event-log-tags
98 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
99 private static final int BACKUP_START_EVENT = 2821;
100 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
101 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
102 private static final int BACKUP_PACKAGE_EVENT = 2824;
103 private static final int BACKUP_SUCCESS_EVENT = 2825;
104
105 private static final int RESTORE_START_EVENT = 2830;
106 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
107 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
108 private static final int RESTORE_PACKAGE_EVENT = 2833;
109 private static final int RESTORE_SUCCESS_EVENT = 2834;
110
Christopher Tatec7b31e32009-06-10 15:49:30 -0700111 // Timeout interval for deciding that a bind or clear-data has taken too long
112 static final long TIMEOUT_INTERVAL = 10 * 1000;
113
Christopher Tate487529a2009-04-29 14:03:25 -0700114 private Context mContext;
115 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700116 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700117 private PowerManager mPowerManager;
118 private AlarmManager mAlarmManager;
119
Christopher Tate73e02522009-07-15 14:18:26 -0700120 boolean mEnabled; // access to this is synchronized on 'this'
121 boolean mProvisioned;
122 PowerManager.WakeLock mWakelock;
123 final BackupHandler mBackupHandler = new BackupHandler();
124 PendingIntent mRunBackupIntent;
125 BroadcastReceiver mRunBackupReceiver;
126 IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700127 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700128 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700129 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700130 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700131 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700132 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700133 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700134
Christopher Tate181fafa2009-05-14 11:12:14 -0700135 BackupRequest(ApplicationInfo app, boolean isFull) {
136 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700137 fullBackup = isFull;
138 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700139
140 public String toString() {
141 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
142 }
Christopher Tate46758122009-05-06 11:22:00 -0700143 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400144 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700145 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700146 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700147
148 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700149 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700150
151 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700152 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700153
Christopher Tate043dadc2009-06-02 16:11:00 -0700154 // The thread performing the sequence of queued backups binds to each app's agent
155 // in succession. Bind notifications are asynchronously delivered through the
156 // Activity Manager; use this lock object to signal when a requested binding has
157 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700158 final Object mAgentConnectLock = new Object();
159 IBackupAgent mConnectedAgent;
160 volatile boolean mConnecting;
Christopher Tate043dadc2009-06-02 16:11:00 -0700161
Christopher Tatec7b31e32009-06-10 15:49:30 -0700162 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700163 final Object mClearDataLock = new Object();
164 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700165
Christopher Tate91717492009-06-26 21:07:13 -0700166 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700167 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700168 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700169 String mCurrentTransport;
170 IBackupTransport mLocalTransport, mGoogleTransport;
171 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700172
Christopher Tate73e02522009-07-15 14:18:26 -0700173 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700174 public IBackupTransport transport;
175 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700176 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700177
Dan Egnor156411d2009-06-26 13:20:02 -0700178 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700179 transport = _transport;
180 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700181 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700182 }
183 }
184
Christopher Tate73e02522009-07-15 14:18:26 -0700185 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700186 public IBackupTransport transport;
187 public PackageInfo packageInfo;
188
189 ClearParams(IBackupTransport _transport, PackageInfo _info) {
190 transport = _transport;
191 packageInfo = _info;
192 }
193 }
194
Christopher Tate5cb400b2009-06-25 16:03:14 -0700195 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700196 File mBaseStateDir;
197 File mDataDir;
198 File mJournalDir;
199 File mJournal;
200 RandomAccessFile mJournalStream;
201
202 // Keep a log of all the apps we've ever backed up
203 private File mEverStored;
204 private RandomAccessFile mEverStoredStream;
205 HashSet<String> mEverStoredApps = new HashSet<String>();
206
Christopher Tateaa088442009-06-16 18:25:46 -0700207
Christopher Tate487529a2009-04-29 14:03:25 -0700208 public BackupManagerService(Context context) {
209 mContext = context;
210 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700211 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700212
Christopher Tateb6787f22009-07-02 17:40:45 -0700213 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
214 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
215
Christopher Tate22b87872009-05-04 16:41:53 -0700216 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700217 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700218 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700219 // !!! TODO: mProvisioned needs to default to 0, not 1.
220 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700221 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700222 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700223 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700224
Christopher Tateb6787f22009-07-02 17:40:45 -0700225 mRunBackupReceiver = new RunBackupReceiver();
226 mRunBackupFilter = new IntentFilter();
227 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
228 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
229
230 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
231 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
232 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
233 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
234 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
235
Christopher Tatecde87f42009-06-12 12:55:53 -0700236 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700237 mJournalDir = new File(mBaseStateDir, "pending");
238 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700239 makeJournalLocked(); // okay because no other threads are running yet
240
Christopher Tate73e02522009-07-15 14:18:26 -0700241 // Set up the various sorts of package tracking we do
242 initPackageTracking();
243
Christopher Tateabce4e82009-06-18 18:35:32 -0700244 // Build our mapping of uid to backup client services. This implicitly
245 // schedules a backup pass on the Package Manager metadata the first
246 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700247 synchronized (mBackupParticipants) {
248 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700249 }
250
Dan Egnor87a02bc2009-06-17 02:30:10 -0700251 // Set up our transport options and initialize the default transport
252 // TODO: Have transports register themselves somehow?
253 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700254 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700255 ComponentName localName = new ComponentName(context, LocalTransport.class);
256 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700257
Christopher Tate91717492009-06-26 21:07:13 -0700258 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700259 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
260 Settings.Secure.BACKUP_TRANSPORT);
261 if ("".equals(mCurrentTransport)) {
262 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700263 }
Christopher Tate91717492009-06-26 21:07:13 -0700264 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
265
266 // Attach to the Google backup transport. When this comes up, it will set
267 // itself as the current transport because we explicitly reset mCurrentTransport
268 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700269 Intent intent = new Intent().setComponent(new ComponentName(
270 "com.google.android.backup",
271 "com.google.android.backup.BackupTransportService"));
272 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700273
Christopher Tatecde87f42009-06-12 12:55:53 -0700274 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700275 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700276 parseLeftoverJournals();
277
Christopher Tateb6787f22009-07-02 17:40:45 -0700278 // Power management
279 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
280
281 // Start the backup passes going
282 setBackupEnabled(areEnabled);
283 }
284
285 private class RunBackupReceiver extends BroadcastReceiver {
286 public void onReceive(Context context, Intent intent) {
287 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
288 if (DEBUG) Log.v(TAG, "Running a backup pass");
289
290 synchronized (mQueueLock) {
291 // acquire a wakelock and pass it to the backup thread. it will
292 // be released once backup concludes.
293 mWakelock.acquire();
294
295 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
296 mBackupHandler.sendMessage(msg);
297 }
298 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700299 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700300 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700301
Christopher Tate73e02522009-07-15 14:18:26 -0700302 private void initPackageTracking() {
303 if (DEBUG) Log.v(TAG, "Initializing package tracking");
304
Christopher Tatee97e8072009-07-15 16:45:50 -0700305 // Keep a log of what apps we've ever backed up. Because we might have
306 // rebooted in the middle of an operation that was removing something from
307 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700308 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700309 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700310 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700311 // If there are previous contents, parse them out then start a new
312 // file to continue the recordkeeping.
313 if (mEverStored.exists()) {
314 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
315 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700316
Christopher Tatedfec20b2009-08-03 15:38:09 -0700317 // parse its existing contents
318 mEverStoredStream.seek(0);
319 temp.seek(0);
320 try {
321 while (true) {
322 PackageInfo info;
323 String pkg = mEverStoredStream.readUTF();
324 try {
325 info = mPackageManager.getPackageInfo(pkg, 0);
326 mEverStoredApps.add(pkg);
327 temp.writeUTF(pkg);
328 if (DEBUG) Log.v(TAG, " + " + pkg);
329 } catch (NameNotFoundException e) {
330 // nope, this package was uninstalled; don't include it
331 if (DEBUG) Log.v(TAG, " - " + pkg);
332 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700333 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700334 } catch (EOFException e) {
335 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700336 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700337
Christopher Tatedfec20b2009-08-03 15:38:09 -0700338 // Once we've rewritten the backup history log, atomically replace the
339 // old one with the new one then reopen the file for continuing use.
340 temp.close();
341 mEverStoredStream.close();
342 tempProcessedFile.renameTo(mEverStored);
343 }
344 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700345 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700346 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700347 } catch (IOException e) {
348 Log.e(TAG, "Unable to open known-stored file!");
349 mEverStoredStream = null;
350 }
351
Christopher Tatee97e8072009-07-15 16:45:50 -0700352 // If we were in the middle of removing something from the ever-backed-up
353 // file, there might be a transient "processed.new" file still present.
354 // We've reconstructed a coherent state at this point though, so we can
355 // safely discard that file now.
356 if (tempProcessedFile.exists()) {
357 tempProcessedFile.delete();
358 }
359
Christopher Tate73e02522009-07-15 14:18:26 -0700360 // Register for broadcasts about package install, etc., so we can
361 // update the provider list.
362 IntentFilter filter = new IntentFilter();
363 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
364 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
365 filter.addDataScheme("package");
366 mContext.registerReceiver(mBroadcastReceiver, filter);
367 }
368
Christopher Tatecde87f42009-06-12 12:55:53 -0700369 private void makeJournalLocked() {
370 try {
371 mJournal = File.createTempFile("journal", null, mJournalDir);
372 mJournalStream = new RandomAccessFile(mJournal, "rwd");
373 } catch (IOException e) {
374 Log.e(TAG, "Unable to write backup journals");
375 mJournal = null;
376 mJournalStream = null;
377 }
378 }
379
380 private void parseLeftoverJournals() {
381 if (mJournal != null) {
382 File[] allJournals = mJournalDir.listFiles();
383 for (File f : allJournals) {
384 if (f.compareTo(mJournal) != 0) {
385 // This isn't the current journal, so it must be a leftover. Read
386 // out the package names mentioned there and schedule them for
387 // backup.
388 try {
389 Log.i(TAG, "Found stale backup journal, scheduling:");
390 RandomAccessFile in = new RandomAccessFile(f, "r");
391 while (true) {
392 String packageName = in.readUTF();
393 Log.i(TAG, " + " + packageName);
394 dataChanged(packageName);
395 }
396 } catch (EOFException e) {
397 // no more data; we're done
398 } catch (Exception e) {
399 // can't read it or other error; just skip it
400 } finally {
401 // close/delete the file
402 f.delete();
403 }
404 }
405 }
406 }
407 }
408
Christopher Tate91717492009-06-26 21:07:13 -0700409 // Add a transport to our set of available backends
410 private void registerTransport(String name, IBackupTransport transport) {
411 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700412 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700413 mTransports.put(name, transport);
414 }
415 }
416
Christopher Tate3799bc22009-05-06 16:13:56 -0700417 // ----- Track installation/removal of packages -----
418 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
419 public void onReceive(Context context, Intent intent) {
420 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
421
422 Uri uri = intent.getData();
423 if (uri == null) {
424 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700425 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700426 String pkgName = uri.getSchemeSpecificPart();
427 if (pkgName == null) {
428 return;
429 }
430
431 String action = intent.getAction();
432 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
433 synchronized (mBackupParticipants) {
434 Bundle extras = intent.getExtras();
435 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
436 // The package was just upgraded
437 updatePackageParticipantsLocked(pkgName);
438 } else {
439 // The package was just added
440 addPackageParticipantsLocked(pkgName);
441 }
442 }
443 }
444 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
445 Bundle extras = intent.getExtras();
446 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
447 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
448 } else {
449 synchronized (mBackupParticipants) {
450 removePackageParticipantsLocked(pkgName);
451 }
452 }
453 }
454 }
455 };
456
Dan Egnor87a02bc2009-06-17 02:30:10 -0700457 // ----- Track connection to GoogleBackupTransport service -----
458 ServiceConnection mGoogleConnection = new ServiceConnection() {
459 public void onServiceConnected(ComponentName name, IBinder service) {
460 if (DEBUG) Log.v(TAG, "Connected to Google transport");
461 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700462 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700463 }
464
465 public void onServiceDisconnected(ComponentName name) {
466 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
467 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700468 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700469 }
470 };
471
Joe Onorato8ad02812009-05-13 01:41:44 -0400472 // ----- Run the actual backup process asynchronously -----
473
Christopher Tate181fafa2009-05-14 11:12:14 -0700474 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400475 public void handleMessage(Message msg) {
476
477 switch (msg.what) {
478 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700479 {
Christopher Tate91717492009-06-26 21:07:13 -0700480 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700481 if (transport == null) {
482 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700483 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700484 break;
485 }
486
Joe Onorato8ad02812009-05-13 01:41:44 -0400487 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700488 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700489 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400490 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700491 // Do we have any work to do?
492 if (mPendingBackups.size() > 0) {
493 for (BackupRequest b: mPendingBackups.values()) {
494 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700495 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700496 Log.v(TAG, "clearing pending backups");
497 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700498
Christopher Tate49401dd2009-07-01 12:34:29 -0700499 // Start a new backup-queue journal file too
500 if (mJournalStream != null) {
501 try {
502 mJournalStream.close();
503 } catch (IOException e) {
504 // don't need to do anything
505 }
506 makeJournalLocked();
507 }
508
509 // At this point, we have started a new journal file, and the old
510 // file identity is being passed to the backup processing thread.
511 // When it completes successfully, that old journal file will be
512 // deleted. If we crash prior to that, the old journal is parsed
513 // at next boot and the journaled requests fulfilled.
514 (new PerformBackupThread(transport, queue, oldJournal)).start();
515 } else {
516 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700517 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700518 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400519 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700520 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700521 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700522
523 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400524 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700525
526 case MSG_RUN_RESTORE:
527 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700528 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400529 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700530 (new PerformRestoreThread(params.transport, params.observer,
531 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700532 break;
533 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700534
535 case MSG_RUN_CLEAR:
536 {
537 ClearParams params = (ClearParams)msg.obj;
538 (new PerformClearThread(params.transport, params.packageInfo)).start();
539 break;
540 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400541 }
542 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400543 }
544
Christopher Tate181fafa2009-05-14 11:12:14 -0700545 // Add the backup agents in the given package to our set of known backup participants.
546 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700547 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700548 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700549 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700550 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700551 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700552 }
553
Christopher Tate181fafa2009-05-14 11:12:14 -0700554 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700555 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700556 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700557 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
558 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700559 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700560 + " uid=" + p.applicationInfo.uid
561 + " killAfterRestore="
562 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
563 + " restoreNeedsApplication="
564 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
565 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700566 }
567 }
568
Dan Egnorefe52642009-06-24 00:16:33 -0700569 for (PackageInfo pkg : targetPkgs) {
570 if (packageName == null || pkg.packageName.equals(packageName)) {
571 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700572 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700573 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700574 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700575 mBackupParticipants.put(uid, set);
576 }
Dan Egnorefe52642009-06-24 00:16:33 -0700577 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700578
579 // If we've never seen this app before, schedule a backup for it
580 if (!mEverStoredApps.contains(pkg.packageName)) {
581 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
582 + " never backed up; scheduling");
583 try {
584 dataChanged(pkg.packageName);
585 } catch (RemoteException e) {
586 // can't happen; it's a local method call
587 }
588 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700589 }
Christopher Tate487529a2009-04-29 14:03:25 -0700590 }
591 }
592
Christopher Tate6785dd82009-06-18 15:58:25 -0700593 // Remove the given package's entry from our known active set. If
594 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700595 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700596 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700597 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700598 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700599 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700600 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700601 int flags = PackageManager.GET_SIGNATURES;
602 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700603 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700604 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700605 }
606 } else {
607 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700608 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700609 }
610 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700611 }
612
Joe Onorato8ad02812009-05-13 01:41:44 -0400613 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700614 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700615 if (DEBUG) {
616 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
617 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700618 for (PackageInfo p : agents) {
619 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700620 }
621 }
Dan Egnorefe52642009-06-24 00:16:33 -0700622 for (PackageInfo pkg : agents) {
623 if (packageName == null || pkg.packageName.equals(packageName)) {
624 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700625 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700626 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700627 // Find the existing entry with the same package name, and remove it.
628 // We can't just remove(app) because the instances are different.
629 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700630 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700631 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700632 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700633 break;
634 }
635 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700636 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700637 mBackupParticipants.delete(uid);
638 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700639 }
640 }
641 }
642 }
643
Christopher Tate181fafa2009-05-14 11:12:14 -0700644 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700645 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700646 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700647 int flags = PackageManager.GET_SIGNATURES;
648 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
649 int N = packages.size();
650 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700651 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700652 try {
653 ApplicationInfo app = pkg.applicationInfo;
654 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
655 || app.backupAgentName == null
656 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
657 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
658 packages.remove(a);
659 }
660 else {
661 // we will need the shared library path, so look that up and store it here
662 app = mPackageManager.getApplicationInfo(pkg.packageName,
663 PackageManager.GET_SHARED_LIBRARY_FILES);
664 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
665 }
666 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700667 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700668 }
669 }
Dan Egnorefe52642009-06-24 00:16:33 -0700670 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700671 }
Christopher Tateaa088442009-06-16 18:25:46 -0700672
Christopher Tate3799bc22009-05-06 16:13:56 -0700673 // Reset the given package's known backup participants. Unlike add/remove, the update
674 // action cannot be passed a null package name.
675 void updatePackageParticipantsLocked(String packageName) {
676 if (packageName == null) {
677 Log.e(TAG, "updatePackageParticipants called with null package name");
678 return;
679 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700680 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700681
682 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700683 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700684 removePackageParticipantsLockedInner(packageName, allApps);
685 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700686 }
687
Christopher Tate73e02522009-07-15 14:18:26 -0700688 // Called from the backup thread: record that the given app has been successfully
689 // backed up at least once
690 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700691 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700692 synchronized (mEverStoredApps) {
693 if (mEverStoredApps.add(packageName)) {
694 try {
695 mEverStoredStream.writeUTF(packageName);
696 } catch (IOException e) {
697 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
698 try {
699 mEverStoredStream.close();
700 } catch (IOException ioe) {
701 // we're dropping it; no need to handle an exception on close here
702 }
703 mEverStoredStream = null;
704 }
705 }
706 }
707 }
708 }
709
Christopher Tatee97e8072009-07-15 16:45:50 -0700710 // Remove our awareness of having ever backed up the given package
711 void removeEverBackedUp(String packageName) {
712 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
713 + ", new set:");
714
715 if (mEverStoredStream != null) {
716 synchronized (mEverStoredApps) {
717 // Rewrite the file and rename to overwrite. If we reboot in the middle,
718 // we'll recognize on initialization time that the package no longer
719 // exists and fix it up then.
720 File tempKnownFile = new File(mBaseStateDir, "processed.new");
721 try {
722 mEverStoredStream.close();
723 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
724 mEverStoredApps.remove(packageName);
725 for (String s : mEverStoredApps) {
726 known.writeUTF(s);
727 if (DEBUG) Log.v(TAG, " " + s);
728 }
729 known.close();
730 tempKnownFile.renameTo(mEverStored);
731 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
732 } catch (IOException e) {
733 // Bad: we couldn't create the new copy. For safety's sake we
734 // abandon the whole process and remove all what's-backed-up
735 // state entirely, meaning we'll force a backup pass for every
736 // participant on the next boot or [re]install.
737 Log.w(TAG, "Error rewriting backed-up set; halting log");
738 mEverStoredStream = null;
739 mEverStoredApps.clear();
740 tempKnownFile.delete();
741 mEverStored.delete();
742 }
743 }
744 }
745 }
746
Dan Egnor87a02bc2009-06-17 02:30:10 -0700747 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700748 private IBackupTransport getTransport(String transportName) {
749 synchronized (mTransports) {
750 IBackupTransport transport = mTransports.get(transportName);
751 if (transport == null) {
752 Log.w(TAG, "Requested unavailable transport: " + transportName);
753 }
754 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700755 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700756 }
757
Christopher Tatedf01dea2009-06-09 20:45:02 -0700758 // fire off a backup agent, blocking until it attaches or times out
759 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
760 IBackupAgent agent = null;
761 synchronized(mAgentConnectLock) {
762 mConnecting = true;
763 mConnectedAgent = null;
764 try {
765 if (mActivityManager.bindBackupAgent(app, mode)) {
766 Log.d(TAG, "awaiting agent for " + app);
767
768 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700769 // only wait 10 seconds for the clear data to happen
770 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
771 while (mConnecting && mConnectedAgent == null
772 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700773 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700774 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700775 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700776 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700777 return null;
778 }
779 }
780
781 // if we timed out with no connect, abort and move on
782 if (mConnecting == true) {
783 Log.w(TAG, "Timeout waiting for agent " + app);
784 return null;
785 }
786 agent = mConnectedAgent;
787 }
788 } catch (RemoteException e) {
789 // can't happen
790 }
791 }
792 return agent;
793 }
794
Christopher Tatec7b31e32009-06-10 15:49:30 -0700795 // clear an application's data, blocking until the operation completes or times out
796 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700797 // Don't wipe packages marked allowClearUserData=false
798 try {
799 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
800 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
801 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
802 + packageName);
803 return;
804 }
805 } catch (NameNotFoundException e) {
806 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
807 return;
808 }
809
Christopher Tatec7b31e32009-06-10 15:49:30 -0700810 ClearDataObserver observer = new ClearDataObserver();
811
812 synchronized(mClearDataLock) {
813 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700814 /* This is causing some critical processes to be killed during setup.
815 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700816 try {
817 mActivityManager.clearApplicationUserData(packageName, observer);
818 } catch (RemoteException e) {
819 // can't happen because the activity manager is in this process
820 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700821 */
822 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700823
824 // only wait 10 seconds for the clear data to happen
825 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
826 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
827 try {
828 mClearDataLock.wait(5000);
829 } catch (InterruptedException e) {
830 // won't happen, but still.
831 mClearingData = false;
832 }
833 }
834 }
835 }
836
837 class ClearDataObserver extends IPackageDataObserver.Stub {
838 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -0700839 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700840 synchronized(mClearDataLock) {
841 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700842 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700843 }
844 }
845 }
846
Christopher Tate043dadc2009-06-02 16:11:00 -0700847 // ----- Back up a set of applications via a worker thread -----
848
849 class PerformBackupThread extends Thread {
850 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700851 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700852 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700853 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700854 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700855
Christopher Tateaa088442009-06-16 18:25:46 -0700856 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700857 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700858 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700859 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700860 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700861
862 try {
863 mStateDir = new File(mBaseStateDir, transport.transportDirName());
864 } catch (RemoteException e) {
865 // can't happen; the transport is local
866 }
867 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700868 }
869
870 @Override
871 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700872 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -0700873 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
874
Christopher Tate79588342009-06-30 16:11:49 -0700875 // Backups run at background priority
876 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
877
Christopher Tate043dadc2009-06-02 16:11:00 -0700878 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -0700879 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
880
881 // The package manager doesn't have a proper <application> etc, but since
882 // it's running here in the system process we can just set up its agent
883 // directly and use a synthetic BackupRequest. We always run this pass
884 // because it's cheap and this way we guarantee that we don't get out of
885 // step even if we're selecting among various transports at run time.
886 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
887 mPackageManager, allAgentPackages());
888 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
889 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate90967f42009-09-20 15:28:33 -0700890
891 // If we haven't stored anything yet, we need to do an init
892 // operation along with recording the metadata blob.
893 boolean needInit = (mEverStoredApps.size() == 0);
894 processOneBackup(pmRequest, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
895 mTransport, needInit);
Dan Egnorbb9001c2009-07-27 12:20:13 -0700896
897 // Now run all the backups in our queue
898 int count = mQueue.size();
899 doQueuedBackups(mTransport);
900
901 // Finally, tear down the transport
902 if (mTransport.finishBackup()) {
903 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
904 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, count, millis);
905 } else {
906 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
907 Log.e(TAG, "Transport error in finishBackup()");
Dan Egnorefe52642009-06-24 00:16:33 -0700908 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700909
Dan Egnorbb9001c2009-07-27 12:20:13 -0700910 if (!mJournal.delete()) {
911 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
912 }
913 } catch (Exception e) {
914 Log.e(TAG, "Error in backup thread", e);
915 } finally {
916 // Only once we're entirely finished do we release the wakelock
917 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -0700918 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700919 }
920
921 private void doQueuedBackups(IBackupTransport transport) {
922 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700923 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700924
Christopher Tate0749dcd2009-08-13 15:13:03 -0700925 // Don't run backup, even if requested, if the target app does not have
926 // the requisite permission
927 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
928 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
929 Log.w(TAG, "Skipping backup of unprivileged package "
930 + request.appInfo.packageName);
931 continue;
932 }
933
Christopher Tate043dadc2009-06-02 16:11:00 -0700934 IBackupAgent agent = null;
935 int mode = (request.fullBackup)
936 ? IApplicationThread.BACKUP_MODE_FULL
937 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
938 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700939 agent = bindToAgentSynchronous(request.appInfo, mode);
940 if (agent != null) {
Christopher Tate90967f42009-09-20 15:28:33 -0700941 processOneBackup(request, agent, transport, false);
Christopher Tate043dadc2009-06-02 16:11:00 -0700942 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700943
944 // unbind even on timeout, just in case
945 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700946 } catch (SecurityException ex) {
947 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700948 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700949 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700950 Log.v(TAG, "bind/backup threw");
951 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700952 }
953 }
954 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700955
Christopher Tate25a747f2009-09-20 12:43:58 -0700956 void processOneBackup(BackupRequest request, IBackupAgent agent,
Christopher Tate90967f42009-09-20 15:28:33 -0700957 IBackupTransport transport, boolean doInit) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700958 final String packageName = request.appInfo.packageName;
Christopher Tate90967f42009-09-20 15:28:33 -0700959 if (DEBUG) Log.d(TAG, "processOneBackup doBackup(" + doInit + ") on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700960
Dan Egnorbb9001c2009-07-27 12:20:13 -0700961 File savedStateName = new File(mStateDir, packageName);
962 File backupDataName = new File(mDataDir, packageName + ".data");
963 File newStateName = new File(mStateDir, packageName + ".new");
964
965 ParcelFileDescriptor savedState = null;
966 ParcelFileDescriptor backupData = null;
967 ParcelFileDescriptor newState = null;
968
969 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700970 try {
971 // Look up the package info & signatures. This is first so that if it
972 // throws an exception, there's no file setup yet that would need to
973 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700974 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
975 // The metadata 'package' is synthetic
976 packInfo = new PackageInfo();
977 packInfo.packageName = packageName;
978 } else {
979 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700980 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700981 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700982
Christopher Tatec7b31e32009-06-10 15:49:30 -0700983 // In a full backup, we pass a null ParcelFileDescriptor as
984 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -0700985 if (!request.fullBackup) {
986 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700987 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -0700988 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
989 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700990
Dan Egnorbb9001c2009-07-27 12:20:13 -0700991 backupData = ParcelFileDescriptor.open(backupDataName,
992 ParcelFileDescriptor.MODE_READ_WRITE |
993 ParcelFileDescriptor.MODE_CREATE |
994 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700995
Dan Egnorbb9001c2009-07-27 12:20:13 -0700996 newState = ParcelFileDescriptor.open(newStateName,
997 ParcelFileDescriptor.MODE_READ_WRITE |
998 ParcelFileDescriptor.MODE_CREATE |
999 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001000
1001 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001002 agent.doBackup(savedState, backupData, newState);
1003 logBackupComplete(packageName);
1004 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001005 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001006 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001007 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1008 backupDataName.delete();
1009 newStateName.delete();
1010 return;
1011 } finally {
1012 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1013 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1014 try { if (newState != null) newState.close(); } catch (IOException e) {}
1015 savedState = backupData = newState = null;
1016 }
1017
1018 // Now propagate the newly-backed-up data to the transport
1019 try {
1020 int size = (int) backupDataName.length();
1021 if (size > 0) {
1022 backupData = ParcelFileDescriptor.open(backupDataName,
1023 ParcelFileDescriptor.MODE_READ_ONLY);
1024
Dan Egnor83861e72009-09-17 16:17:55 -07001025 // TODO - We call finishBackup() for each application backed up, because
1026 // we need to know now whether it succeeded or failed. Instead, we should
1027 // hold off on finishBackup() until the end, which implies holding off on
1028 // renaming *all* the output state files (see below) until that happens.
1029
Christopher Tate25a747f2009-09-20 12:43:58 -07001030 if (!transport.performBackup(packInfo, backupData, doInit) ||
Dan Egnor83861e72009-09-17 16:17:55 -07001031 !transport.finishBackup()) {
1032 throw new Exception("Backup transport failed");
1033 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001034 } else {
1035 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1036 }
1037
1038 // After successful transport, delete the now-stale data
1039 // and juggle the files so that next time we supply the agent
1040 // with the new state file it just created.
1041 backupDataName.delete();
1042 newStateName.renameTo(savedStateName);
1043 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1044 } catch (Exception e) {
1045 Log.e(TAG, "Transport error backing up " + packageName, e);
1046 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1047 return;
1048 } finally {
1049 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001050 }
1051 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001052 }
1053
Christopher Tatedf01dea2009-06-09 20:45:02 -07001054
1055 // ----- Restore handling -----
1056
Christopher Tateabce4e82009-06-18 18:35:32 -07001057 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001058 // Allow unsigned apps, but not signed on one device and unsigned on the other
1059 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001060 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1061 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001062 if ((storedSigs == null || storedSigs.length == 0)
1063 && (deviceSigs == null || deviceSigs.length == 0)) {
1064 return true;
1065 }
1066 if (storedSigs == null || deviceSigs == null) {
1067 return false;
1068 }
1069
Christopher Tateabce4e82009-06-18 18:35:32 -07001070 // !!! TODO: this demands that every stored signature match one
1071 // that is present on device, and does not demand the converse.
1072 // Is this this right policy?
1073 int nStored = storedSigs.length;
1074 int nDevice = deviceSigs.length;
1075
1076 for (int i=0; i < nStored; i++) {
1077 boolean match = false;
1078 for (int j=0; j < nDevice; j++) {
1079 if (storedSigs[i].equals(deviceSigs[j])) {
1080 match = true;
1081 break;
1082 }
1083 }
1084 if (!match) {
1085 return false;
1086 }
1087 }
1088 return true;
1089 }
1090
Christopher Tatedf01dea2009-06-09 20:45:02 -07001091 class PerformRestoreThread extends Thread {
1092 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001093 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001094 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001095 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001096
Christopher Tate5cbbf562009-06-22 16:44:51 -07001097 class RestoreRequest {
1098 public PackageInfo app;
1099 public int storedAppVersion;
1100
1101 RestoreRequest(PackageInfo _app, int _version) {
1102 app = _app;
1103 storedAppVersion = _version;
1104 }
1105 }
1106
Christopher Tate7d562ec2009-06-25 18:03:43 -07001107 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001108 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001109 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001110 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001111 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001112 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001113
1114 try {
1115 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1116 } catch (RemoteException e) {
1117 // can't happen; the transport is local
1118 }
1119 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001120 }
1121
1122 @Override
1123 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001124 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001125 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001126 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001127 /**
1128 * Restore sequence:
1129 *
Dan Egnorefe52642009-06-24 00:16:33 -07001130 * 1. get the restore set description for our identity
1131 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001132 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001133 * 3. for each app in the restore queue:
1134 * 3.a. clear the app data
1135 * 3.b. get the restore data for the app from the transport
1136 * 3.c. launch the backup agent for the app
1137 * 3.d. agent.doRestore() with the data from the server
1138 * 3.e. unbind the agent [and kill the app?]
1139 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001140 *
1141 * On errors, we try our best to recover and move on to the next
1142 * application, but if necessary we abort the whole operation --
1143 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001144 */
1145
Christopher Tate7d562ec2009-06-25 18:03:43 -07001146 int error = -1; // assume error
1147
Dan Egnorefe52642009-06-24 00:16:33 -07001148 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001149 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001150 // TODO: Log this before getAvailableRestoreSets, somehow
1151 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName());
Christopher Tateabce4e82009-06-18 18:35:32 -07001152
Dan Egnorefe52642009-06-24 00:16:33 -07001153 // Get the list of all packages which have backup enabled.
1154 // (Include the Package Manager metadata pseudo-package first.)
1155 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1156 PackageInfo omPackage = new PackageInfo();
1157 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1158 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001159
Dan Egnorefe52642009-06-24 00:16:33 -07001160 List<PackageInfo> agentPackages = allAgentPackages();
1161 restorePackages.addAll(agentPackages);
1162
Christopher Tate7d562ec2009-06-25 18:03:43 -07001163 // let the observer know that we're running
1164 if (mObserver != null) {
1165 try {
1166 // !!! TODO: get an actual count from the transport after
1167 // its startRestore() runs?
1168 mObserver.restoreStarting(restorePackages.size());
1169 } catch (RemoteException e) {
1170 Log.d(TAG, "Restore observer died at restoreStarting");
1171 mObserver = null;
1172 }
1173 }
1174
Dan Egnor156411d2009-06-26 13:20:02 -07001175 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -07001176 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001177 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001178 return;
1179 }
1180
1181 String packageName = mTransport.nextRestorePackage();
1182 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001183 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001184 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001185 return;
1186 } else if (packageName.equals("")) {
1187 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001188 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1189 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001190 return;
1191 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1192 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1193 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001194 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1195 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001196 return;
1197 }
1198
1199 // Pull the Package Manager metadata from the restore set first
1200 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1201 mPackageManager, agentPackages);
1202 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1203
Christopher Tate8c032472009-07-02 14:28:47 -07001204 // Verify that the backup set includes metadata. If not, we can't do
1205 // signature/version verification etc, so we simply do not proceed with
1206 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001207 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001208 Log.e(TAG, "No restore metadata available, so not restoring settings");
1209 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1210 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001211 return;
1212 }
1213
Christopher Tate7d562ec2009-06-25 18:03:43 -07001214 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001215 for (;;) {
1216 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001217
Dan Egnorefe52642009-06-24 00:16:33 -07001218 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001219 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001220 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001221 return;
1222 } else if (packageName.equals("")) {
1223 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001224 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001225
Christopher Tate7d562ec2009-06-25 18:03:43 -07001226 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001227 try {
1228 mObserver.onUpdate(count);
1229 } catch (RemoteException e) {
1230 Log.d(TAG, "Restore observer died in onUpdate");
1231 mObserver = null;
1232 }
1233 }
1234
Dan Egnorefe52642009-06-24 00:16:33 -07001235 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1236 if (metaInfo == null) {
1237 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001238 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1239 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001240 continue;
1241 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001242
Dan Egnorbb9001c2009-07-27 12:20:13 -07001243 PackageInfo packageInfo;
1244 try {
1245 int flags = PackageManager.GET_SIGNATURES;
1246 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1247 } catch (NameNotFoundException e) {
1248 Log.e(TAG, "Invalid package restoring data", e);
1249 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1250 "Package missing on device");
1251 continue;
1252 }
1253
Dan Egnorefe52642009-06-24 00:16:33 -07001254 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255 String message = "Version " + metaInfo.versionCode
1256 + " > installed version " + packageInfo.versionCode;
1257 Log.w(TAG, "Package " + packageName + ": " + message);
1258 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001259 continue;
1260 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001261
Dan Egnorefe52642009-06-24 00:16:33 -07001262 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1263 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001264 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1265 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001266 continue;
1267 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001268
Dan Egnorefe52642009-06-24 00:16:33 -07001269 if (DEBUG) Log.v(TAG, "Package " + packageName
1270 + " restore version [" + metaInfo.versionCode
1271 + "] is compatible with installed version ["
1272 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001273
Christopher Tate5e1ab332009-09-01 20:32:49 -07001274 // Now perform the actual restore: first clear the app's data
1275 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001276 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001277
1278 // Then set up and bind the agent (with a restricted Application object
1279 // unless the application says otherwise)
1280 boolean useRealApp = (packageInfo.applicationInfo.flags
1281 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1282 if (DEBUG && useRealApp) {
1283 Log.v(TAG, "agent requires real Application subclass for restore");
1284 }
Dan Egnorefe52642009-06-24 00:16:33 -07001285 IBackupAgent agent = bindToAgentSynchronous(
1286 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001287 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1288 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001289 if (agent == null) {
1290 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001291 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1292 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001293 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001294 }
1295
Christopher Tate5e1ab332009-09-01 20:32:49 -07001296 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001297 try {
1298 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001299 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001300 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001301 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001302 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001303
1304 // The agent was probably running with a stub Application object,
1305 // which isn't a valid run mode for the main app logic. Shut
1306 // down the app so that next time it's launched, it gets the
1307 // usual full initialization.
1308 if ((packageInfo.applicationInfo.flags
1309 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1310 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1311 + packageInfo.applicationInfo.processName);
1312 mActivityManager.killApplicationProcess(
1313 packageInfo.applicationInfo.processName,
1314 packageInfo.applicationInfo.uid);
1315 }
Dan Egnorefe52642009-06-24 00:16:33 -07001316 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001317 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001318
1319 // if we get this far, report success to the observer
1320 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001321 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1322 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1323 } catch (Exception e) {
1324 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001325 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001326 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1327
Dan Egnorefe52642009-06-24 00:16:33 -07001328 try {
1329 mTransport.finishRestore();
1330 } catch (RemoteException e) {
1331 Log.e(TAG, "Error finishing restore", e);
1332 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001333
1334 if (mObserver != null) {
1335 try {
1336 mObserver.restoreFinished(error);
1337 } catch (RemoteException e) {
1338 Log.d(TAG, "Restore observer died at restoreFinished");
1339 }
1340 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001341
1342 // done; we can finally release the wakelock
1343 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001344 }
1345 }
1346
Dan Egnorefe52642009-06-24 00:16:33 -07001347 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1348 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001349 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001350 final String packageName = app.packageName;
1351
Dan Egnorbb9001c2009-07-27 12:20:13 -07001352 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001353
Christopher Tate0749dcd2009-08-13 15:13:03 -07001354 // Don't restore to unprivileged packages
1355 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1356 packageName) != PackageManager.PERMISSION_GRANTED) {
1357 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1358 }
1359
Christopher Tatec7b31e32009-06-10 15:49:30 -07001360 // !!! TODO: get the dirs from the transport
1361 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001362 File newStateName = new File(mStateDir, packageName + ".new");
1363 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001364
Dan Egnorbb9001c2009-07-27 12:20:13 -07001365 ParcelFileDescriptor backupData = null;
1366 ParcelFileDescriptor newState = null;
1367
1368 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001369 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001370 backupData = ParcelFileDescriptor.open(backupDataName,
1371 ParcelFileDescriptor.MODE_READ_WRITE |
1372 ParcelFileDescriptor.MODE_CREATE |
1373 ParcelFileDescriptor.MODE_TRUNCATE);
1374
1375 if (!mTransport.getRestoreData(backupData)) {
1376 Log.e(TAG, "Error getting restore data for " + packageName);
1377 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1378 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001379 }
1380
1381 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001383 backupData = ParcelFileDescriptor.open(backupDataName,
1384 ParcelFileDescriptor.MODE_READ_ONLY);
1385
Dan Egnorbb9001c2009-07-27 12:20:13 -07001386 newState = ParcelFileDescriptor.open(newStateName,
1387 ParcelFileDescriptor.MODE_READ_WRITE |
1388 ParcelFileDescriptor.MODE_CREATE |
1389 ParcelFileDescriptor.MODE_TRUNCATE);
1390
1391 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001392
1393 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001394 //
1395 // !!! TODO: the restored data should be migrated on the server
1396 // side into the current dataset. In that case the new state file
1397 // we just created would reflect the data already extant in the
1398 // backend, so there'd be nothing more to do. Until that happens,
1399 // however, we need to make sure that we record the data to the
1400 // current backend dataset. (Yes, this means shipping the data over
1401 // the wire in both directions. That's bad, but consistency comes
1402 // first, then efficiency.) Once we introduce server-side data
1403 // migration to the newly-restored device's dataset, we will change
1404 // the following from a discard of the newly-written state to the
1405 // "correct" operation of renaming into the canonical state blob.
1406 newStateName.delete(); // TODO: remove; see above comment
1407 //newStateName.renameTo(savedStateName); // TODO: replace with this
1408
Dan Egnorbb9001c2009-07-27 12:20:13 -07001409 int size = (int) backupDataName.length();
1410 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001411 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001412 Log.e(TAG, "Error restoring data for " + packageName, e);
1413 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1414
Christopher Tate96733042009-07-20 14:49:13 -07001415 // If the agent fails restore, it might have put the app's data
1416 // into an incoherent state. For consistency we wipe its data
1417 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001418 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001419 } finally {
1420 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1422 try { if (newState != null) newState.close(); } catch (IOException e) {}
1423 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001424 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001425 }
1426 }
1427
Christopher Tateee0e78a2009-07-02 11:17:03 -07001428 class PerformClearThread extends Thread {
1429 IBackupTransport mTransport;
1430 PackageInfo mPackage;
1431
1432 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1433 mTransport = transport;
1434 mPackage = packageInfo;
1435 }
1436
1437 @Override
1438 public void run() {
1439 try {
1440 // Clear the on-device backup state to ensure a full backup next time
1441 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1442 File stateFile = new File(stateDir, mPackage.packageName);
1443 stateFile.delete();
1444
1445 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001446 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001447 mTransport.clearBackupData(mPackage);
1448 } catch (RemoteException e) {
1449 // can't happen; the transport is local
1450 } finally {
1451 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001452 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001453 mTransport.finishBackup();
1454 } catch (RemoteException e) {
1455 // can't happen; the transport is local
1456 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001457
1458 // Last but not least, release the cpu
1459 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001460 }
1461 }
1462 }
1463
Christopher Tatedf01dea2009-06-09 20:45:02 -07001464
Christopher Tate487529a2009-04-29 14:03:25 -07001465 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001466
Christopher Tatea8bf8152009-04-30 11:36:21 -07001467 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001468 // Record that we need a backup pass for the caller. Since multiple callers
1469 // may share a uid, we need to note all candidates within that uid and schedule
1470 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001472
Christopher Tate63d27002009-06-16 17:16:42 -07001473 // If the caller does not hold the BACKUP permission, it can only request a
1474 // backup of its own data.
1475 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001476 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001477 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1478 targets = mBackupParticipants.get(Binder.getCallingUid());
1479 } else {
1480 // a caller with full permission can ask to back up any participating app
1481 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001482 targets = new HashSet<ApplicationInfo>();
1483 int N = mBackupParticipants.size();
1484 for (int i = 0; i < N; i++) {
1485 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1486 if (s != null) {
1487 targets.addAll(s);
1488 }
1489 }
1490 }
Christopher Tate487529a2009-04-29 14:03:25 -07001491 if (targets != null) {
1492 synchronized (mQueueLock) {
1493 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001494 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001495 // validate the caller-supplied package name against the known set of
1496 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001497 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001498 // Add the caller to the set of pending backups. If there is
1499 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001500 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001501 if (mPendingBackups.put(app, req) == null) {
1502 // Journal this request in case of crash. The put()
1503 // operation returned null when this package was not already
1504 // in the set; we want to avoid touching the disk redundantly.
1505 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001506
Christopher Tate22b60d82009-07-07 16:36:02 -07001507 if (DEBUG) {
1508 int numKeys = mPendingBackups.size();
1509 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1510 for (BackupRequest b : mPendingBackups.values()) {
1511 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1512 }
1513 }
1514 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001515 }
1516 }
Christopher Tate487529a2009-04-29 14:03:25 -07001517 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001518 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001519 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1520 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001521 }
1522 }
Christopher Tate46758122009-05-06 11:22:00 -07001523
Christopher Tatecde87f42009-06-12 12:55:53 -07001524 private void writeToJournalLocked(String str) {
1525 if (mJournalStream != null) {
1526 try {
1527 mJournalStream.writeUTF(str);
1528 } catch (IOException e) {
1529 Log.e(TAG, "Error writing to backup journal");
1530 mJournalStream = null;
1531 mJournal = null;
1532 }
1533 }
1534 }
1535
Christopher Tateee0e78a2009-07-02 11:17:03 -07001536 // Clear the given package's backup data from the current transport
1537 public void clearBackupData(String packageName) {
1538 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1539 PackageInfo info;
1540 try {
1541 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1542 } catch (NameNotFoundException e) {
1543 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1544 return;
1545 }
1546
1547 // If the caller does not hold the BACKUP permission, it can only request a
1548 // wipe of its own backed-up data.
1549 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001550 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001551 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1552 apps = mBackupParticipants.get(Binder.getCallingUid());
1553 } else {
1554 // a caller with full permission can ask to back up any participating app
1555 // !!! TODO: allow data-clear of ANY app?
1556 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1557 apps = new HashSet<ApplicationInfo>();
1558 int N = mBackupParticipants.size();
1559 for (int i = 0; i < N; i++) {
1560 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1561 if (s != null) {
1562 apps.addAll(s);
1563 }
1564 }
1565 }
1566
1567 // now find the given package in the set of candidate apps
1568 for (ApplicationInfo app : apps) {
1569 if (app.packageName.equals(packageName)) {
1570 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1571 // found it; fire off the clear request
1572 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001573 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001574 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001575 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1576 new ClearParams(getTransport(mCurrentTransport), info));
1577 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001578 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001579 }
1580 break;
1581 }
1582 }
1583 }
1584
Christopher Tateace7f092009-06-15 18:07:25 -07001585 // Run a backup pass immediately for any applications that have declared
1586 // that they have pending updates.
1587 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001589
Christopher Tateace7f092009-06-15 18:07:25 -07001590 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001591 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001592 try {
1593 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1594 mRunBackupIntent.send();
1595 } catch (PendingIntent.CanceledException e) {
1596 // should never happen
1597 Log.e(TAG, "run-backup intent cancelled!");
1598 }
Christopher Tate46758122009-05-06 11:22:00 -07001599 }
1600 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001601
Christopher Tate8031a3d2009-07-06 16:36:05 -07001602 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001603 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1605 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001606
1607 boolean wasEnabled = mEnabled;
1608 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001609 Settings.Secure.putInt(mContext.getContentResolver(),
1610 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001611 mEnabled = enable;
1612 }
1613
Christopher Tate49401dd2009-07-01 12:34:29 -07001614 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001615 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001616 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001617 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001618 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001619 // No longer enabled, so stop running backups
1620 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001621 }
1622 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001623 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001624
Christopher Tate8031a3d2009-07-06 16:36:05 -07001625 // Mark the backup service as having been provisioned
1626 public void setBackupProvisioned(boolean available) {
1627 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1628 "setBackupProvisioned");
1629
1630 boolean wasProvisioned = mProvisioned;
1631 synchronized (this) {
1632 Settings.Secure.putInt(mContext.getContentResolver(),
1633 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1634 mProvisioned = available;
1635 }
1636
1637 synchronized (mQueueLock) {
1638 if (available && !wasProvisioned && mEnabled) {
1639 // we're now good to go, so start the backup alarms
1640 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1641 } else if (!available) {
1642 // No longer enabled, so stop running backups
1643 Log.w(TAG, "Backup service no longer provisioned");
1644 mAlarmManager.cancel(mRunBackupIntent);
1645 }
1646 }
1647 }
1648
1649 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1650 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1651 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1652 BACKUP_INTERVAL, mRunBackupIntent);
1653 }
1654
Christopher Tate6ef58a12009-06-29 14:56:28 -07001655 // Report whether the backup mechanism is currently enabled
1656 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001658 return mEnabled; // no need to synchronize just to read it
1659 }
1660
Christopher Tate91717492009-06-26 21:07:13 -07001661 // Report the name of the currently active transport
1662 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001664 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001665 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001666 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001667 }
1668
Christopher Tate91717492009-06-26 21:07:13 -07001669 // Report all known, available backup transports
1670 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001672
Christopher Tate91717492009-06-26 21:07:13 -07001673 String[] list = null;
1674 ArrayList<String> known = new ArrayList<String>();
1675 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1676 if (entry.getValue() != null) {
1677 known.add(entry.getKey());
1678 }
1679 }
1680
1681 if (known.size() > 0) {
1682 list = new String[known.size()];
1683 known.toArray(list);
1684 }
1685 return list;
1686 }
1687
1688 // Select which transport to use for the next backup operation. If the given
1689 // name is not one of the available transports, no action is taken and the method
1690 // returns null.
1691 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001693
1694 synchronized (mTransports) {
1695 String prevTransport = null;
1696 if (mTransports.get(transport) != null) {
1697 prevTransport = mCurrentTransport;
1698 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001699 Settings.Secure.putString(mContext.getContentResolver(),
1700 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001701 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1702 + " returning " + prevTransport);
1703 } else {
1704 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1705 }
1706 return prevTransport;
1707 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001708 }
1709
1710 // Callback: a requested backup agent has been instantiated. This should only
1711 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001712 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001713 synchronized(mAgentConnectLock) {
1714 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1715 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1716 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1717 mConnectedAgent = agent;
1718 mConnecting = false;
1719 } else {
1720 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1721 + " claiming agent connected");
1722 }
1723 mAgentConnectLock.notifyAll();
1724 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001725 }
1726
1727 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1728 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001729 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001730 public void agentDisconnected(String packageName) {
1731 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001732 synchronized(mAgentConnectLock) {
1733 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1734 mConnectedAgent = null;
1735 mConnecting = false;
1736 } else {
1737 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1738 + " claiming agent disconnected");
1739 }
1740 mAgentConnectLock.notifyAll();
1741 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001742 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001743
Christopher Tate8c850b72009-06-07 19:33:20 -07001744 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001745 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001747
1748 synchronized(this) {
1749 if (mActiveRestoreSession != null) {
1750 Log.d(TAG, "Restore session requested but one already active");
1751 return null;
1752 }
Christopher Tate91717492009-06-26 21:07:13 -07001753 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001754 }
1755 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001756 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001757
Christopher Tate9b3905c2009-06-08 15:24:01 -07001758 // ----- Restore session -----
1759
1760 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001761 private static final String TAG = "RestoreSession";
1762
Christopher Tate9b3905c2009-06-08 15:24:01 -07001763 private IBackupTransport mRestoreTransport = null;
1764 RestoreSet[] mRestoreSets = null;
1765
Christopher Tate91717492009-06-26 21:07:13 -07001766 RestoreSession(String transport) {
1767 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001768 }
1769
1770 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07001771 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04001772 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001773 "getAvailableRestoreSets");
1774
Christopher Tatef68eb502009-06-16 11:02:01 -07001775 try {
Christopher Tate43383042009-07-13 15:17:13 -07001776 if (mRestoreTransport == null) {
1777 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07001778 return null;
1779 }
1780 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001781 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001782 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001783 }
1784 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07001785 } catch (Exception e) {
1786 Log.e(TAG, "Error in getAvailableRestoreSets", e);
1787 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001788 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001789 }
1790
Dan Egnor0084da52009-07-29 12:57:16 -07001791 public synchronized int performRestore(long token, IRestoreObserver observer) {
1792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1793 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001794
Christopher Tatef2c321a2009-08-10 15:43:36 -07001795 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
1796 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001797
Dan Egnor0084da52009-07-29 12:57:16 -07001798 if (mRestoreTransport == null || mRestoreSets == null) {
1799 Log.e(TAG, "Ignoring performRestore() with no restore set");
1800 return -1;
1801 }
1802
1803 for (int i = 0; i < mRestoreSets.length; i++) {
1804 if (token == mRestoreSets[i].token) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001805 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07001806 mWakelock.acquire();
1807 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1808 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
1809 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001810 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07001811 return 0;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001812 }
1813 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07001814
1815 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07001816 return -1;
1817 }
1818
Dan Egnor0084da52009-07-29 12:57:16 -07001819 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04001820 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001821 "endRestoreSession");
1822
Dan Egnor0084da52009-07-29 12:57:16 -07001823 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001824
Dan Egnor0084da52009-07-29 12:57:16 -07001825 synchronized (this) {
1826 try {
1827 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
1828 } catch (Exception e) {
1829 Log.e(TAG, "Error in finishRestore", e);
1830 } finally {
1831 mRestoreTransport = null;
1832 }
1833 }
1834
1835 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07001836 if (BackupManagerService.this.mActiveRestoreSession == this) {
1837 BackupManagerService.this.mActiveRestoreSession = null;
1838 } else {
1839 Log.e(TAG, "ending non-current restore session");
1840 }
1841 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001842 }
1843 }
1844
Christopher Tate043dadc2009-06-02 16:11:00 -07001845
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001846 @Override
1847 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1848 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001849 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1850 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001851 pw.println("Available transports:");
1852 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001853 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1854 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001855 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001856 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001857 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001858 for (int i=0; i<N; i++) {
1859 int uid = mBackupParticipants.keyAt(i);
1860 pw.print(" uid: ");
1861 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001862 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1863 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001864 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001865 }
1866 }
Christopher Tate73e02522009-07-15 14:18:26 -07001867 pw.println("Ever backed up: " + mEverStoredApps.size());
1868 for (String pkg : mEverStoredApps) {
1869 pw.println(" " + pkg);
1870 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001871 pw.println("Pending: " + mPendingBackups.size());
1872 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001873 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001874 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001875 }
1876 }
Christopher Tate487529a2009-04-29 14:03:25 -07001877}