blob: 15290c182a9e77cdcdde8e7ae79941b01ff4d8ab [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 Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070049import android.os.SystemClock;
50import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.util.Log;
52import android.util.SparseArray;
53
54import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070055import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070056import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070057import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070058
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
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 Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
82 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Christopher Tate8031a3d2009-07-06 16:36:05 -070088 // The amount of time between the initial provisioning of the device and
89 // the first backup pass.
90 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
91
Christopher Tate4cc86e12009-09-21 19:36:51 -070092 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
93 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
94 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070095 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070096 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070097 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070098 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -070099 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700100
Dan Egnorbb9001c2009-07-27 12:20:13 -0700101 // Event tags -- see system/core/logcat/event-log-tags
102 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
103 private static final int BACKUP_START_EVENT = 2821;
104 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
105 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
106 private static final int BACKUP_PACKAGE_EVENT = 2824;
107 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700108 private static final int BACKUP_RESET_EVENT = 2826;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700109
110 private static final int RESTORE_START_EVENT = 2830;
111 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
112 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
113 private static final int RESTORE_PACKAGE_EVENT = 2833;
114 private static final int RESTORE_SUCCESS_EVENT = 2834;
115
Christopher Tatec7b31e32009-06-10 15:49:30 -0700116 // Timeout interval for deciding that a bind or clear-data has taken too long
117 static final long TIMEOUT_INTERVAL = 10 * 1000;
118
Christopher Tate487529a2009-04-29 14:03:25 -0700119 private Context mContext;
120 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700121 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700122 private PowerManager mPowerManager;
123 private AlarmManager mAlarmManager;
124
Christopher Tate73e02522009-07-15 14:18:26 -0700125 boolean mEnabled; // access to this is synchronized on 'this'
126 boolean mProvisioned;
127 PowerManager.WakeLock mWakelock;
128 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700129 PendingIntent mRunBackupIntent, mRunInitIntent;
130 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700131 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700132 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700133 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700134 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700135 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700137 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700138
Christopher Tate181fafa2009-05-14 11:12:14 -0700139 BackupRequest(ApplicationInfo app, boolean isFull) {
140 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700141 fullBackup = isFull;
142 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700143
144 public String toString() {
145 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
146 }
Christopher Tate46758122009-05-06 11:22:00 -0700147 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400148 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700149 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700150 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700151
152 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700153 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700154
155 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700156 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700157
Christopher Tate043dadc2009-06-02 16:11:00 -0700158 // The thread performing the sequence of queued backups binds to each app's agent
159 // in succession. Bind notifications are asynchronously delivered through the
160 // Activity Manager; use this lock object to signal when a requested binding has
161 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700162 final Object mAgentConnectLock = new Object();
163 IBackupAgent mConnectedAgent;
164 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700165 volatile boolean mBackupOrRestoreInProgress = false;
Christopher Tate043dadc2009-06-02 16:11:00 -0700166
Christopher Tatec7b31e32009-06-10 15:49:30 -0700167 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700168 final Object mClearDataLock = new Object();
169 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700170
Christopher Tate91717492009-06-26 21:07:13 -0700171 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700172 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700173 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700174 String mCurrentTransport;
175 IBackupTransport mLocalTransport, mGoogleTransport;
176 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700177
Christopher Tate73e02522009-07-15 14:18:26 -0700178 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700179 public IBackupTransport transport;
180 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700181 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700182
Dan Egnor156411d2009-06-26 13:20:02 -0700183 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700184 transport = _transport;
185 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700186 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700187 }
188 }
189
Christopher Tate73e02522009-07-15 14:18:26 -0700190 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700191 public IBackupTransport transport;
192 public PackageInfo packageInfo;
193
194 ClearParams(IBackupTransport _transport, PackageInfo _info) {
195 transport = _transport;
196 packageInfo = _info;
197 }
198 }
199
Christopher Tate5cb400b2009-06-25 16:03:14 -0700200 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700201 File mBaseStateDir;
202 File mDataDir;
203 File mJournalDir;
204 File mJournal;
205 RandomAccessFile mJournalStream;
206
207 // Keep a log of all the apps we've ever backed up
208 private File mEverStored;
209 private RandomAccessFile mEverStoredStream;
210 HashSet<String> mEverStoredApps = new HashSet<String>();
211
Christopher Tate4cc86e12009-09-21 19:36:51 -0700212 // Persistently track the need to do a full init
213 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
214 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700215 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700216
Christopher Tate487529a2009-04-29 14:03:25 -0700217 public BackupManagerService(Context context) {
218 mContext = context;
219 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700220 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700221
Christopher Tateb6787f22009-07-02 17:40:45 -0700222 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
223 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
224
Christopher Tate22b87872009-05-04 16:41:53 -0700225 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700226 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700227 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700228 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700229 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700230 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700231 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700232
Christopher Tate4cc86e12009-09-21 19:36:51 -0700233 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700234 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700235 IntentFilter filter = new IntentFilter();
236 filter.addAction(RUN_BACKUP_ACTION);
237 context.registerReceiver(mRunBackupReceiver, filter,
238 android.Manifest.permission.BACKUP, null);
239
240 mRunInitReceiver = new RunInitializeReceiver();
241 filter = new IntentFilter();
242 filter.addAction(RUN_INITIALIZE_ACTION);
243 context.registerReceiver(mRunInitReceiver, filter,
244 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700245
246 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700247 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
248 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
249
Christopher Tate4cc86e12009-09-21 19:36:51 -0700250 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
251 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
252 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
253
Christopher Tatecde87f42009-06-12 12:55:53 -0700254 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700255 mJournalDir = new File(mBaseStateDir, "pending");
256 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700257 makeJournalLocked(); // okay because no other threads are running yet
258
Christopher Tate73e02522009-07-15 14:18:26 -0700259 // Set up the various sorts of package tracking we do
260 initPackageTracking();
261
Christopher Tateabce4e82009-06-18 18:35:32 -0700262 // Build our mapping of uid to backup client services. This implicitly
263 // schedules a backup pass on the Package Manager metadata the first
264 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700265 synchronized (mBackupParticipants) {
266 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700267 }
268
Dan Egnor87a02bc2009-06-17 02:30:10 -0700269 // Set up our transport options and initialize the default transport
270 // TODO: Have transports register themselves somehow?
271 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700272 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700273 ComponentName localName = new ComponentName(context, LocalTransport.class);
274 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700275
Christopher Tate91717492009-06-26 21:07:13 -0700276 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700277 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
278 Settings.Secure.BACKUP_TRANSPORT);
279 if ("".equals(mCurrentTransport)) {
280 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700281 }
Christopher Tate91717492009-06-26 21:07:13 -0700282 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
283
284 // Attach to the Google backup transport. When this comes up, it will set
285 // itself as the current transport because we explicitly reset mCurrentTransport
286 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700287 Intent intent = new Intent().setComponent(new ComponentName(
288 "com.google.android.backup",
289 "com.google.android.backup.BackupTransportService"));
290 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700291
Christopher Tatecde87f42009-06-12 12:55:53 -0700292 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700293 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700294 parseLeftoverJournals();
295
Christopher Tateb6787f22009-07-02 17:40:45 -0700296 // Power management
297 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
298
299 // Start the backup passes going
300 setBackupEnabled(areEnabled);
301 }
302
303 private class RunBackupReceiver extends BroadcastReceiver {
304 public void onReceive(Context context, Intent intent) {
305 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700306 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700307 if (mPendingInits.size() > 0) {
308 // If there are pending init operations, we process those
309 // and then settle into the usual periodic backup schedule.
310 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
311 try {
312 mAlarmManager.cancel(mRunInitIntent);
313 mRunInitIntent.send();
314 } catch (PendingIntent.CanceledException ce) {
315 Log.e(TAG, "Run init intent cancelled");
316 // can't really do more than bail here
317 }
318 } else {
319 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700320 // fully set up, in the middle of a backup already,
321 // or racing with an initialize pass.
322 if (mEnabled && mProvisioned
323 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700324 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700325 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700326
327 // Acquire the wakelock and pass it to the backup thread. it will
328 // be released once backup concludes.
329 mWakelock.acquire();
330
331 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
332 mBackupHandler.sendMessage(msg);
333 } else {
334 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700335 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700336 }
337 }
338 }
339 }
340 }
341 }
342
343 private class RunInitializeReceiver extends BroadcastReceiver {
344 public void onReceive(Context context, Intent intent) {
345 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
346 synchronized (mQueueLock) {
347 if (DEBUG) Log.v(TAG, "Running a device init");
348 mInitInProgress = true;
349
350 // Acquire the wakelock and pass it to the init thread. it will
351 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700352 mWakelock.acquire();
353
Christopher Tate4cc86e12009-09-21 19:36:51 -0700354 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700355 mBackupHandler.sendMessage(msg);
356 }
357 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700358 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700359 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700360
Christopher Tate73e02522009-07-15 14:18:26 -0700361 private void initPackageTracking() {
362 if (DEBUG) Log.v(TAG, "Initializing package tracking");
363
Christopher Tatee97e8072009-07-15 16:45:50 -0700364 // Keep a log of what apps we've ever backed up. Because we might have
365 // rebooted in the middle of an operation that was removing something from
366 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700367 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700368 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700369 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700370 // If there are previous contents, parse them out then start a new
371 // file to continue the recordkeeping.
372 if (mEverStored.exists()) {
373 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
374 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700375
Christopher Tatedfec20b2009-08-03 15:38:09 -0700376 // parse its existing contents
377 mEverStoredStream.seek(0);
378 temp.seek(0);
379 try {
380 while (true) {
381 PackageInfo info;
382 String pkg = mEverStoredStream.readUTF();
383 try {
384 info = mPackageManager.getPackageInfo(pkg, 0);
385 mEverStoredApps.add(pkg);
386 temp.writeUTF(pkg);
387 if (DEBUG) Log.v(TAG, " + " + pkg);
388 } catch (NameNotFoundException e) {
389 // nope, this package was uninstalled; don't include it
390 if (DEBUG) Log.v(TAG, " - " + pkg);
391 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700392 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700393 } catch (EOFException e) {
394 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700395 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700396
Christopher Tatedfec20b2009-08-03 15:38:09 -0700397 // Once we've rewritten the backup history log, atomically replace the
398 // old one with the new one then reopen the file for continuing use.
399 temp.close();
400 mEverStoredStream.close();
401 tempProcessedFile.renameTo(mEverStored);
402 }
403 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700404 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700405 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700406 } catch (IOException e) {
407 Log.e(TAG, "Unable to open known-stored file!");
408 mEverStoredStream = null;
409 }
410
Christopher Tatee97e8072009-07-15 16:45:50 -0700411 // If we were in the middle of removing something from the ever-backed-up
412 // file, there might be a transient "processed.new" file still present.
413 // We've reconstructed a coherent state at this point though, so we can
414 // safely discard that file now.
415 if (tempProcessedFile.exists()) {
416 tempProcessedFile.delete();
417 }
418
Christopher Tate73e02522009-07-15 14:18:26 -0700419 // Register for broadcasts about package install, etc., so we can
420 // update the provider list.
421 IntentFilter filter = new IntentFilter();
422 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
423 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
424 filter.addDataScheme("package");
425 mContext.registerReceiver(mBroadcastReceiver, filter);
426 }
427
Christopher Tatecde87f42009-06-12 12:55:53 -0700428 private void makeJournalLocked() {
429 try {
430 mJournal = File.createTempFile("journal", null, mJournalDir);
431 mJournalStream = new RandomAccessFile(mJournal, "rwd");
432 } catch (IOException e) {
433 Log.e(TAG, "Unable to write backup journals");
434 mJournal = null;
435 mJournalStream = null;
436 }
437 }
438
439 private void parseLeftoverJournals() {
440 if (mJournal != null) {
441 File[] allJournals = mJournalDir.listFiles();
442 for (File f : allJournals) {
443 if (f.compareTo(mJournal) != 0) {
444 // This isn't the current journal, so it must be a leftover. Read
445 // out the package names mentioned there and schedule them for
446 // backup.
447 try {
448 Log.i(TAG, "Found stale backup journal, scheduling:");
449 RandomAccessFile in = new RandomAccessFile(f, "r");
450 while (true) {
451 String packageName = in.readUTF();
452 Log.i(TAG, " + " + packageName);
453 dataChanged(packageName);
454 }
455 } catch (EOFException e) {
456 // no more data; we're done
457 } catch (Exception e) {
458 // can't read it or other error; just skip it
459 } finally {
460 // close/delete the file
461 f.delete();
462 }
463 }
464 }
465 }
466 }
467
Christopher Tate4cc86e12009-09-21 19:36:51 -0700468 // Maintain persistent state around whether need to do an initialize operation.
469 // Must be called with the queue lock held.
470 void recordInitPendingLocked(boolean isPending, String transportName) {
471 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
472 + " on transport " + transportName);
473 try {
474 IBackupTransport transport = getTransport(transportName);
475 String transportDirName = transport.transportDirName();
476 File stateDir = new File(mBaseStateDir, transportDirName);
477 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
478
479 if (isPending) {
480 // We need an init before we can proceed with sending backup data.
481 // Record that with an entry in our set of pending inits, as well as
482 // journaling it via creation of a sentinel file.
483 mPendingInits.add(transportName);
484 try {
485 (new FileOutputStream(initPendingFile)).close();
486 } catch (IOException ioe) {
487 // Something is badly wrong with our permissions; just try to move on
488 }
489 } else {
490 // No more initialization needed; wipe the journal and reset our state.
491 initPendingFile.delete();
492 mPendingInits.remove(transportName);
493 }
494 } catch (RemoteException e) {
495 // can't happen; the transport is local
496 }
497 }
498
Christopher Tated55e18a2009-09-21 10:12:59 -0700499 // Reset all of our bookkeeping, in response to having been told that
500 // the backend data has been wiped [due to idle expiry, for example],
501 // so we must re-upload all saved settings.
502 void resetBackupState(File stateFileDir) {
503 synchronized (mQueueLock) {
504 // Wipe the "what we've ever backed up" tracking
505 try {
506 // close the ever-stored journal...
507 if (mEverStoredStream != null) {
508 mEverStoredStream.close();
509 }
510 // ... so we can delete it and start over
511 mEverStored.delete();
512 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
513 } catch (IOException e) {
514 Log.e(TAG, "Unable to open known-stored file!");
515 mEverStoredStream = null;
516 }
517 mEverStoredApps.clear();
518
519 // Remove all the state files
520 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700521 // ... but don't touch the needs-init sentinel
522 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
523 sf.delete();
524 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700525 }
526
527 // Enqueue a new backup of every participant
528 int N = mBackupParticipants.size();
529 for (int i=0; i<N; i++) {
530 int uid = mBackupParticipants.keyAt(i);
531 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
532 for (ApplicationInfo app: participants) {
533 try {
534 dataChanged(app.packageName);
535 } catch (RemoteException e) {
536 // can't happen; we're in the same process
537 }
538 }
539 }
540 }
541 }
542
Christopher Tate91717492009-06-26 21:07:13 -0700543 // Add a transport to our set of available backends
544 private void registerTransport(String name, IBackupTransport transport) {
545 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700546 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700547 mTransports.put(name, transport);
548 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700549
550 // If the init sentinel file exists, we need to be sure to perform the init
551 // as soon as practical. We also create the state directory at registration
552 // time to ensure it's present from the outset.
553 try {
554 String transportName = transport.transportDirName();
555 File stateDir = new File(mBaseStateDir, transportName);
556 stateDir.mkdirs();
557
558 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
559 if (initSentinel.exists()) {
560 synchronized (mQueueLock) {
561 mPendingInits.add(transportName);
562
563 // TODO: pick a better starting time than now + 1 minute
564 long delay = 1000 * 60; // one minute, in milliseconds
565 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
566 System.currentTimeMillis() + delay, mRunInitIntent);
567 }
568 }
569 } catch (RemoteException e) {
570 // can't happen, the transport is local
571 }
Christopher Tate91717492009-06-26 21:07:13 -0700572 }
573
Christopher Tate3799bc22009-05-06 16:13:56 -0700574 // ----- Track installation/removal of packages -----
575 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
576 public void onReceive(Context context, Intent intent) {
577 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
578
579 Uri uri = intent.getData();
580 if (uri == null) {
581 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700582 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700583 String pkgName = uri.getSchemeSpecificPart();
584 if (pkgName == null) {
585 return;
586 }
587
588 String action = intent.getAction();
589 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
590 synchronized (mBackupParticipants) {
591 Bundle extras = intent.getExtras();
592 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
593 // The package was just upgraded
594 updatePackageParticipantsLocked(pkgName);
595 } else {
596 // The package was just added
597 addPackageParticipantsLocked(pkgName);
598 }
599 }
600 }
601 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
602 Bundle extras = intent.getExtras();
603 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
604 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
605 } else {
606 synchronized (mBackupParticipants) {
607 removePackageParticipantsLocked(pkgName);
608 }
609 }
610 }
611 }
612 };
613
Dan Egnor87a02bc2009-06-17 02:30:10 -0700614 // ----- Track connection to GoogleBackupTransport service -----
615 ServiceConnection mGoogleConnection = new ServiceConnection() {
616 public void onServiceConnected(ComponentName name, IBinder service) {
617 if (DEBUG) Log.v(TAG, "Connected to Google transport");
618 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700619 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700620 }
621
622 public void onServiceDisconnected(ComponentName name) {
623 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
624 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700625 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700626 }
627 };
628
Joe Onorato8ad02812009-05-13 01:41:44 -0400629 // ----- Run the actual backup process asynchronously -----
630
Christopher Tate181fafa2009-05-14 11:12:14 -0700631 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400632 public void handleMessage(Message msg) {
633
634 switch (msg.what) {
635 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700636 {
Christopher Tate91717492009-06-26 21:07:13 -0700637 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700638 if (transport == null) {
639 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700640 synchronized (mQueueLock) {
641 mBackupOrRestoreInProgress = false;
642 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700643 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700644 break;
645 }
646
Joe Onorato8ad02812009-05-13 01:41:44 -0400647 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700648 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700649 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400650 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700651 // Do we have any work to do?
652 if (mPendingBackups.size() > 0) {
653 for (BackupRequest b: mPendingBackups.values()) {
654 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700655 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700656 Log.v(TAG, "clearing pending backups");
657 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700658
Christopher Tate49401dd2009-07-01 12:34:29 -0700659 // Start a new backup-queue journal file too
660 if (mJournalStream != null) {
661 try {
662 mJournalStream.close();
663 } catch (IOException e) {
664 // don't need to do anything
665 }
666 makeJournalLocked();
667 }
668
669 // At this point, we have started a new journal file, and the old
670 // file identity is being passed to the backup processing thread.
671 // When it completes successfully, that old journal file will be
672 // deleted. If we crash prior to that, the old journal is parsed
673 // at next boot and the journaled requests fulfilled.
674 (new PerformBackupThread(transport, queue, oldJournal)).start();
675 } else {
676 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700677 synchronized (mQueueLock) {
678 mBackupOrRestoreInProgress = false;
679 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700680 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700681 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400682 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700683 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700684 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700685
686 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400687 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700688
689 case MSG_RUN_RESTORE:
690 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700691 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400692 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700693 (new PerformRestoreThread(params.transport, params.observer,
694 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700695 break;
696 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700697
698 case MSG_RUN_CLEAR:
699 {
700 ClearParams params = (ClearParams)msg.obj;
701 (new PerformClearThread(params.transport, params.packageInfo)).start();
702 break;
703 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700704
705 case MSG_RUN_INITIALIZE:
706 {
707 HashSet<String> queue;
708
709 // Snapshot the pending-init queue and work on that
710 synchronized (mQueueLock) {
711 queue = new HashSet<String>(mPendingInits);
712 mPendingInits.clear();
713 }
714
715 (new PerformInitializeThread(queue)).start();
716 break;
717 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400718 }
719 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400720 }
721
Christopher Tate181fafa2009-05-14 11:12:14 -0700722 // Add the backup agents in the given package to our set of known backup participants.
723 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700724 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700725 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700726 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700727 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700728 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700729 }
730
Christopher Tate181fafa2009-05-14 11:12:14 -0700731 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700732 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700733 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700734 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
735 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700736 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700737 + " uid=" + p.applicationInfo.uid
738 + " killAfterRestore="
739 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
740 + " restoreNeedsApplication="
741 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
742 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700743 }
744 }
745
Dan Egnorefe52642009-06-24 00:16:33 -0700746 for (PackageInfo pkg : targetPkgs) {
747 if (packageName == null || pkg.packageName.equals(packageName)) {
748 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700749 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700750 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700751 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700752 mBackupParticipants.put(uid, set);
753 }
Dan Egnorefe52642009-06-24 00:16:33 -0700754 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700755
756 // If we've never seen this app before, schedule a backup for it
757 if (!mEverStoredApps.contains(pkg.packageName)) {
758 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
759 + " never backed up; scheduling");
760 try {
761 dataChanged(pkg.packageName);
762 } catch (RemoteException e) {
763 // can't happen; it's a local method call
764 }
765 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700766 }
Christopher Tate487529a2009-04-29 14:03:25 -0700767 }
768 }
769
Christopher Tate6785dd82009-06-18 15:58:25 -0700770 // Remove the given package's entry from our known active set. If
771 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700772 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700773 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700774 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700775 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700776 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700777 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700778 int flags = PackageManager.GET_SIGNATURES;
779 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700780 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700781 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700782 }
783 } else {
784 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700785 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700786 }
787 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700788 }
789
Joe Onorato8ad02812009-05-13 01:41:44 -0400790 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700791 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700792 if (DEBUG) {
793 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
794 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700795 for (PackageInfo p : agents) {
796 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700797 }
798 }
Dan Egnorefe52642009-06-24 00:16:33 -0700799 for (PackageInfo pkg : agents) {
800 if (packageName == null || pkg.packageName.equals(packageName)) {
801 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700802 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700803 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700804 // Find the existing entry with the same package name, and remove it.
805 // We can't just remove(app) because the instances are different.
806 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700807 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700808 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700809 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700810 break;
811 }
812 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700813 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700814 mBackupParticipants.delete(uid);
815 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700816 }
817 }
818 }
819 }
820
Christopher Tate181fafa2009-05-14 11:12:14 -0700821 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700822 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700823 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700824 int flags = PackageManager.GET_SIGNATURES;
825 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
826 int N = packages.size();
827 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700828 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700829 try {
830 ApplicationInfo app = pkg.applicationInfo;
831 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
832 || app.backupAgentName == null
833 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
834 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
835 packages.remove(a);
836 }
837 else {
838 // we will need the shared library path, so look that up and store it here
839 app = mPackageManager.getApplicationInfo(pkg.packageName,
840 PackageManager.GET_SHARED_LIBRARY_FILES);
841 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
842 }
843 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700844 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700845 }
846 }
Dan Egnorefe52642009-06-24 00:16:33 -0700847 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700848 }
Christopher Tateaa088442009-06-16 18:25:46 -0700849
Christopher Tate3799bc22009-05-06 16:13:56 -0700850 // Reset the given package's known backup participants. Unlike add/remove, the update
851 // action cannot be passed a null package name.
852 void updatePackageParticipantsLocked(String packageName) {
853 if (packageName == null) {
854 Log.e(TAG, "updatePackageParticipants called with null package name");
855 return;
856 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700857 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700858
859 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700860 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700861 removePackageParticipantsLockedInner(packageName, allApps);
862 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700863 }
864
Christopher Tate73e02522009-07-15 14:18:26 -0700865 // Called from the backup thread: record that the given app has been successfully
866 // backed up at least once
867 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700868 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700869 synchronized (mEverStoredApps) {
870 if (mEverStoredApps.add(packageName)) {
871 try {
872 mEverStoredStream.writeUTF(packageName);
873 } catch (IOException e) {
874 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
875 try {
876 mEverStoredStream.close();
877 } catch (IOException ioe) {
878 // we're dropping it; no need to handle an exception on close here
879 }
880 mEverStoredStream = null;
881 }
882 }
883 }
884 }
885 }
886
Christopher Tatee97e8072009-07-15 16:45:50 -0700887 // Remove our awareness of having ever backed up the given package
888 void removeEverBackedUp(String packageName) {
889 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
890 + ", new set:");
891
892 if (mEverStoredStream != null) {
893 synchronized (mEverStoredApps) {
894 // Rewrite the file and rename to overwrite. If we reboot in the middle,
895 // we'll recognize on initialization time that the package no longer
896 // exists and fix it up then.
897 File tempKnownFile = new File(mBaseStateDir, "processed.new");
898 try {
899 mEverStoredStream.close();
900 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
901 mEverStoredApps.remove(packageName);
902 for (String s : mEverStoredApps) {
903 known.writeUTF(s);
904 if (DEBUG) Log.v(TAG, " " + s);
905 }
906 known.close();
907 tempKnownFile.renameTo(mEverStored);
908 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
909 } catch (IOException e) {
910 // Bad: we couldn't create the new copy. For safety's sake we
911 // abandon the whole process and remove all what's-backed-up
912 // state entirely, meaning we'll force a backup pass for every
913 // participant on the next boot or [re]install.
914 Log.w(TAG, "Error rewriting backed-up set; halting log");
915 mEverStoredStream = null;
916 mEverStoredApps.clear();
917 tempKnownFile.delete();
918 mEverStored.delete();
919 }
920 }
921 }
922 }
923
Dan Egnor87a02bc2009-06-17 02:30:10 -0700924 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700925 private IBackupTransport getTransport(String transportName) {
926 synchronized (mTransports) {
927 IBackupTransport transport = mTransports.get(transportName);
928 if (transport == null) {
929 Log.w(TAG, "Requested unavailable transport: " + transportName);
930 }
931 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700932 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700933 }
934
Christopher Tatedf01dea2009-06-09 20:45:02 -0700935 // fire off a backup agent, blocking until it attaches or times out
936 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
937 IBackupAgent agent = null;
938 synchronized(mAgentConnectLock) {
939 mConnecting = true;
940 mConnectedAgent = null;
941 try {
942 if (mActivityManager.bindBackupAgent(app, mode)) {
943 Log.d(TAG, "awaiting agent for " + app);
944
945 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700946 // only wait 10 seconds for the clear data to happen
947 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
948 while (mConnecting && mConnectedAgent == null
949 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700950 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700951 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700952 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700953 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700954 return null;
955 }
956 }
957
958 // if we timed out with no connect, abort and move on
959 if (mConnecting == true) {
960 Log.w(TAG, "Timeout waiting for agent " + app);
961 return null;
962 }
963 agent = mConnectedAgent;
964 }
965 } catch (RemoteException e) {
966 // can't happen
967 }
968 }
969 return agent;
970 }
971
Christopher Tatec7b31e32009-06-10 15:49:30 -0700972 // clear an application's data, blocking until the operation completes or times out
973 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700974 // Don't wipe packages marked allowClearUserData=false
975 try {
976 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
977 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
978 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
979 + packageName);
980 return;
981 }
982 } catch (NameNotFoundException e) {
983 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
984 return;
985 }
986
Christopher Tatec7b31e32009-06-10 15:49:30 -0700987 ClearDataObserver observer = new ClearDataObserver();
988
989 synchronized(mClearDataLock) {
990 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700991 /* This is causing some critical processes to be killed during setup.
992 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700993 try {
994 mActivityManager.clearApplicationUserData(packageName, observer);
995 } catch (RemoteException e) {
996 // can't happen because the activity manager is in this process
997 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700998 */
999 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001000
1001 // only wait 10 seconds for the clear data to happen
1002 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1003 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1004 try {
1005 mClearDataLock.wait(5000);
1006 } catch (InterruptedException e) {
1007 // won't happen, but still.
1008 mClearingData = false;
1009 }
1010 }
1011 }
1012 }
1013
1014 class ClearDataObserver extends IPackageDataObserver.Stub {
1015 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -07001016 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001017 synchronized(mClearDataLock) {
1018 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001019 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001020 }
1021 }
1022 }
1023
Christopher Tate043dadc2009-06-02 16:11:00 -07001024 // ----- Back up a set of applications via a worker thread -----
1025
1026 class PerformBackupThread extends Thread {
1027 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001028 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001029 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001030 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001031 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001032
Christopher Tateaa088442009-06-16 18:25:46 -07001033 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001034 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001035 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001036 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001037 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001038
1039 try {
1040 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1041 } catch (RemoteException e) {
1042 // can't happen; the transport is local
1043 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001044 }
1045
1046 @Override
1047 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001048 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001049 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001050 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1051
Christopher Tate79588342009-06-30 16:11:49 -07001052 // Backups run at background priority
1053 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1054
Christopher Tate043dadc2009-06-02 16:11:00 -07001055 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001056 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001057
1058 // If we haven't stored anything yet, we need to do an init operation.
1059 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
1060 status = mTransport.initializeDevice();
1061 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001062
1063 // The package manager doesn't have a proper <application> etc, but since
1064 // it's running here in the system process we can just set up its agent
1065 // directly and use a synthetic BackupRequest. We always run this pass
1066 // because it's cheap and this way we guarantee that we don't get out of
1067 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001068 if (status == BackupConstants.TRANSPORT_OK) {
1069 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1070 mPackageManager, allAgentPackages());
1071 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1072 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1073 status = processOneBackup(pmRequest,
1074 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1075 }
Christopher Tate90967f42009-09-20 15:28:33 -07001076
Dan Egnor01445162009-09-21 17:04:05 -07001077 if (status == BackupConstants.TRANSPORT_OK) {
1078 // Now run all the backups in our queue
1079 status = doQueuedBackups(mTransport);
1080 }
1081
1082 if (status == BackupConstants.TRANSPORT_OK) {
1083 // Tell the transport to finish everything it has buffered
1084 status = mTransport.finishBackup();
1085 if (status == BackupConstants.TRANSPORT_OK) {
1086 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1087 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1088 } else {
1089 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
1090 Log.e(TAG, "Transport error in finishBackup()");
1091 }
1092 }
1093
Dan Egnor01445162009-09-21 17:04:05 -07001094 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001095 // The backend reports that our dataset has been wiped. We need to
1096 // reset all of our bookkeeping and instead run a new backup pass for
1097 // everything.
1098 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1099 resetBackupState(mStateDir);
1100 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001101 }
1102 } catch (Exception e) {
1103 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001104 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001105 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001106 // If things went wrong, we need to re-stage the apps we had expected
1107 // to be backing up in this pass. This journals the package names in
1108 // the current active pending-backup file, not in the we are holding
1109 // here in mJournal.
1110 if (status != BackupConstants.TRANSPORT_OK) {
1111 Log.w(TAG, "Backup pass unsuccessful, restaging");
1112 for (BackupRequest req : mQueue) {
1113 try {
1114 dataChanged(req.appInfo.packageName);
1115 } catch (RemoteException e) {
1116 // can't happen; it's a local call
1117 }
1118 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001119
1120 // We also want to reset the backup schedule based on whatever
1121 // the transport suggests by way of retry/backoff time.
1122 try {
1123 startBackupAlarmsLocked(mTransport.requestBackupTime());
1124 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001125 }
1126
1127 // Either backup was successful, in which case we of course do not need
1128 // this pass's journal any more; or it failed, in which case we just
1129 // re-enqueued all of these packages in the current active journal.
1130 // Either way, we no longer need this pass's journal.
1131 if (!mJournal.delete()) {
1132 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1133 }
1134
Christopher Tate21ab6a52009-09-24 18:01:46 -07001135 // Only once we're entirely finished do we indicate our completion
1136 // and release the wakelock
1137 synchronized (mQueueLock) {
1138 mBackupOrRestoreInProgress = false;
1139 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001140 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001141 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001142 }
1143
Dan Egnor01445162009-09-21 17:04:05 -07001144 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001145 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001146 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001147
Christopher Tate0749dcd2009-08-13 15:13:03 -07001148 // Don't run backup, even if requested, if the target app does not have
1149 // the requisite permission
1150 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1151 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1152 Log.w(TAG, "Skipping backup of unprivileged package "
1153 + request.appInfo.packageName);
1154 continue;
1155 }
1156
Christopher Tate043dadc2009-06-02 16:11:00 -07001157 IBackupAgent agent = null;
1158 int mode = (request.fullBackup)
1159 ? IApplicationThread.BACKUP_MODE_FULL
1160 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1161 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001162 agent = bindToAgentSynchronous(request.appInfo, mode);
1163 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001164 int result = processOneBackup(request, agent, transport);
1165 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001166 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001167 } catch (SecurityException ex) {
1168 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001169 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001170 } finally {
1171 try { // unbind even on timeout, just in case
1172 mActivityManager.unbindBackupAgent(request.appInfo);
1173 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001174 }
1175 }
Dan Egnor01445162009-09-21 17:04:05 -07001176
1177 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001178 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001179
Dan Egnor01445162009-09-21 17:04:05 -07001180 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1181 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001182 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001183 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001184
Dan Egnorbb9001c2009-07-27 12:20:13 -07001185 File savedStateName = new File(mStateDir, packageName);
1186 File backupDataName = new File(mDataDir, packageName + ".data");
1187 File newStateName = new File(mStateDir, packageName + ".new");
1188
1189 ParcelFileDescriptor savedState = null;
1190 ParcelFileDescriptor backupData = null;
1191 ParcelFileDescriptor newState = null;
1192
1193 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001194 try {
1195 // Look up the package info & signatures. This is first so that if it
1196 // throws an exception, there's no file setup yet that would need to
1197 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001198 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1199 // The metadata 'package' is synthetic
1200 packInfo = new PackageInfo();
1201 packInfo.packageName = packageName;
1202 } else {
1203 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001204 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001205 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001206
Christopher Tatec7b31e32009-06-10 15:49:30 -07001207 // In a full backup, we pass a null ParcelFileDescriptor as
1208 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001209 if (!request.fullBackup) {
1210 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001211 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001212 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1213 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001214
Dan Egnorbb9001c2009-07-27 12:20:13 -07001215 backupData = ParcelFileDescriptor.open(backupDataName,
1216 ParcelFileDescriptor.MODE_READ_WRITE |
1217 ParcelFileDescriptor.MODE_CREATE |
1218 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001219
Dan Egnorbb9001c2009-07-27 12:20:13 -07001220 newState = ParcelFileDescriptor.open(newStateName,
1221 ParcelFileDescriptor.MODE_READ_WRITE |
1222 ParcelFileDescriptor.MODE_CREATE |
1223 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001224
1225 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001226 agent.doBackup(savedState, backupData, newState);
1227 logBackupComplete(packageName);
1228 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001229 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001230 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001231 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1232 backupDataName.delete();
1233 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001234 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001235 } finally {
1236 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1237 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1238 try { if (newState != null) newState.close(); } catch (IOException e) {}
1239 savedState = backupData = newState = null;
1240 }
1241
1242 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001243 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001244 try {
1245 int size = (int) backupDataName.length();
1246 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001247 if (result == BackupConstants.TRANSPORT_OK) {
1248 backupData = ParcelFileDescriptor.open(backupDataName,
1249 ParcelFileDescriptor.MODE_READ_ONLY);
1250 result = transport.performBackup(packInfo, backupData);
1251 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001252
Dan Egnor83861e72009-09-17 16:17:55 -07001253 // TODO - We call finishBackup() for each application backed up, because
1254 // we need to know now whether it succeeded or failed. Instead, we should
1255 // hold off on finishBackup() until the end, which implies holding off on
1256 // renaming *all* the output state files (see below) until that happens.
1257
Dan Egnor01445162009-09-21 17:04:05 -07001258 if (result == BackupConstants.TRANSPORT_OK) {
1259 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001260 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001261 } else {
1262 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1263 }
1264
1265 // After successful transport, delete the now-stale data
1266 // and juggle the files so that next time we supply the agent
1267 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001268 if (result == BackupConstants.TRANSPORT_OK) {
1269 backupDataName.delete();
1270 newStateName.renameTo(savedStateName);
1271 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1272 } else {
1273 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1274 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001275 } catch (Exception e) {
1276 Log.e(TAG, "Transport error backing up " + packageName, e);
1277 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001278 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001279 } finally {
1280 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001281 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001282
Dan Egnor01445162009-09-21 17:04:05 -07001283 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001284 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001285 }
1286
Christopher Tatedf01dea2009-06-09 20:45:02 -07001287
1288 // ----- Restore handling -----
1289
Christopher Tateabce4e82009-06-18 18:35:32 -07001290 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001291 // Allow unsigned apps, but not signed on one device and unsigned on the other
1292 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001293 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1294 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001295 if ((storedSigs == null || storedSigs.length == 0)
1296 && (deviceSigs == null || deviceSigs.length == 0)) {
1297 return true;
1298 }
1299 if (storedSigs == null || deviceSigs == null) {
1300 return false;
1301 }
1302
Christopher Tateabce4e82009-06-18 18:35:32 -07001303 // !!! TODO: this demands that every stored signature match one
1304 // that is present on device, and does not demand the converse.
1305 // Is this this right policy?
1306 int nStored = storedSigs.length;
1307 int nDevice = deviceSigs.length;
1308
1309 for (int i=0; i < nStored; i++) {
1310 boolean match = false;
1311 for (int j=0; j < nDevice; j++) {
1312 if (storedSigs[i].equals(deviceSigs[j])) {
1313 match = true;
1314 break;
1315 }
1316 }
1317 if (!match) {
1318 return false;
1319 }
1320 }
1321 return true;
1322 }
1323
Christopher Tatedf01dea2009-06-09 20:45:02 -07001324 class PerformRestoreThread extends Thread {
1325 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001326 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001327 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001328 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001329
Christopher Tate5cbbf562009-06-22 16:44:51 -07001330 class RestoreRequest {
1331 public PackageInfo app;
1332 public int storedAppVersion;
1333
1334 RestoreRequest(PackageInfo _app, int _version) {
1335 app = _app;
1336 storedAppVersion = _version;
1337 }
1338 }
1339
Christopher Tate7d562ec2009-06-25 18:03:43 -07001340 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001341 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001342 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001343 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001344 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001345 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001346
1347 try {
1348 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1349 } catch (RemoteException e) {
1350 // can't happen; the transport is local
1351 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001352 }
1353
1354 @Override
1355 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001356 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001357 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001358 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001359 /**
1360 * Restore sequence:
1361 *
Dan Egnorefe52642009-06-24 00:16:33 -07001362 * 1. get the restore set description for our identity
1363 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001364 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001365 * 3. for each app in the restore queue:
1366 * 3.a. clear the app data
1367 * 3.b. get the restore data for the app from the transport
1368 * 3.c. launch the backup agent for the app
1369 * 3.d. agent.doRestore() with the data from the server
1370 * 3.e. unbind the agent [and kill the app?]
1371 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001372 *
1373 * On errors, we try our best to recover and move on to the next
1374 * application, but if necessary we abort the whole operation --
1375 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001376 */
1377
Christopher Tate7d562ec2009-06-25 18:03:43 -07001378 int error = -1; // assume error
1379
Dan Egnorefe52642009-06-24 00:16:33 -07001380 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001381 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001383 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001384
Dan Egnorefe52642009-06-24 00:16:33 -07001385 // Get the list of all packages which have backup enabled.
1386 // (Include the Package Manager metadata pseudo-package first.)
1387 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1388 PackageInfo omPackage = new PackageInfo();
1389 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1390 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001391
Dan Egnorefe52642009-06-24 00:16:33 -07001392 List<PackageInfo> agentPackages = allAgentPackages();
1393 restorePackages.addAll(agentPackages);
1394
Christopher Tate7d562ec2009-06-25 18:03:43 -07001395 // let the observer know that we're running
1396 if (mObserver != null) {
1397 try {
1398 // !!! TODO: get an actual count from the transport after
1399 // its startRestore() runs?
1400 mObserver.restoreStarting(restorePackages.size());
1401 } catch (RemoteException e) {
1402 Log.d(TAG, "Restore observer died at restoreStarting");
1403 mObserver = null;
1404 }
1405 }
1406
Dan Egnor01445162009-09-21 17:04:05 -07001407 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1408 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001409 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001410 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001411 return;
1412 }
1413
1414 String packageName = mTransport.nextRestorePackage();
1415 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001416 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001417 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001418 return;
1419 } else if (packageName.equals("")) {
1420 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1422 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001423 return;
1424 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1425 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1426 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001427 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1428 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001429 return;
1430 }
1431
1432 // Pull the Package Manager metadata from the restore set first
1433 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1434 mPackageManager, agentPackages);
1435 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1436
Christopher Tate8c032472009-07-02 14:28:47 -07001437 // Verify that the backup set includes metadata. If not, we can't do
1438 // signature/version verification etc, so we simply do not proceed with
1439 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001440 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001441 Log.e(TAG, "No restore metadata available, so not restoring settings");
1442 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1443 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001444 return;
1445 }
1446
Christopher Tate7d562ec2009-06-25 18:03:43 -07001447 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001448 for (;;) {
1449 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001450
Dan Egnorefe52642009-06-24 00:16:33 -07001451 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001452 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001453 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001454 return;
1455 } else if (packageName.equals("")) {
1456 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001457 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001458
Christopher Tate7d562ec2009-06-25 18:03:43 -07001459 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001460 try {
1461 mObserver.onUpdate(count);
1462 } catch (RemoteException e) {
1463 Log.d(TAG, "Restore observer died in onUpdate");
1464 mObserver = null;
1465 }
1466 }
1467
Dan Egnorefe52642009-06-24 00:16:33 -07001468 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1469 if (metaInfo == null) {
1470 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1472 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001473 continue;
1474 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001475
Dan Egnorbb9001c2009-07-27 12:20:13 -07001476 PackageInfo packageInfo;
1477 try {
1478 int flags = PackageManager.GET_SIGNATURES;
1479 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1480 } catch (NameNotFoundException e) {
1481 Log.e(TAG, "Invalid package restoring data", e);
1482 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1483 "Package missing on device");
1484 continue;
1485 }
1486
Dan Egnorefe52642009-06-24 00:16:33 -07001487 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001488 String message = "Version " + metaInfo.versionCode
1489 + " > installed version " + packageInfo.versionCode;
1490 Log.w(TAG, "Package " + packageName + ": " + message);
1491 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001492 continue;
1493 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001494
Dan Egnorefe52642009-06-24 00:16:33 -07001495 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1496 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001497 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1498 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001499 continue;
1500 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001501
Dan Egnorefe52642009-06-24 00:16:33 -07001502 if (DEBUG) Log.v(TAG, "Package " + packageName
1503 + " restore version [" + metaInfo.versionCode
1504 + "] is compatible with installed version ["
1505 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001506
Christopher Tate5e1ab332009-09-01 20:32:49 -07001507 // Now perform the actual restore: first clear the app's data
1508 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001509 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001510
1511 // Then set up and bind the agent (with a restricted Application object
1512 // unless the application says otherwise)
1513 boolean useRealApp = (packageInfo.applicationInfo.flags
1514 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1515 if (DEBUG && useRealApp) {
1516 Log.v(TAG, "agent requires real Application subclass for restore");
1517 }
Dan Egnorefe52642009-06-24 00:16:33 -07001518 IBackupAgent agent = bindToAgentSynchronous(
1519 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001520 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1521 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001522 if (agent == null) {
1523 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001524 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1525 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001526 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001527 }
1528
Christopher Tate5e1ab332009-09-01 20:32:49 -07001529 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001530 try {
1531 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001532 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001533 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001534 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001535 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001536
1537 // The agent was probably running with a stub Application object,
1538 // which isn't a valid run mode for the main app logic. Shut
1539 // down the app so that next time it's launched, it gets the
1540 // usual full initialization.
1541 if ((packageInfo.applicationInfo.flags
1542 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1543 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1544 + packageInfo.applicationInfo.processName);
1545 mActivityManager.killApplicationProcess(
1546 packageInfo.applicationInfo.processName,
1547 packageInfo.applicationInfo.uid);
1548 }
Dan Egnorefe52642009-06-24 00:16:33 -07001549 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001550 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001551
1552 // if we get this far, report success to the observer
1553 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001554 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1555 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1556 } catch (Exception e) {
1557 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001558 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001559 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1560
Dan Egnorefe52642009-06-24 00:16:33 -07001561 try {
1562 mTransport.finishRestore();
1563 } catch (RemoteException e) {
1564 Log.e(TAG, "Error finishing restore", e);
1565 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001566
1567 if (mObserver != null) {
1568 try {
1569 mObserver.restoreFinished(error);
1570 } catch (RemoteException e) {
1571 Log.d(TAG, "Restore observer died at restoreFinished");
1572 }
1573 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001574
1575 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001576 synchronized (mQueueLock) {
1577 mBackupOrRestoreInProgress = false;
1578 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001579 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001580 }
1581 }
1582
Dan Egnorefe52642009-06-24 00:16:33 -07001583 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1584 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001585 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001586 final String packageName = app.packageName;
1587
Dan Egnorbb9001c2009-07-27 12:20:13 -07001588 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001589
Christopher Tate0749dcd2009-08-13 15:13:03 -07001590 // Don't restore to unprivileged packages
1591 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1592 packageName) != PackageManager.PERMISSION_GRANTED) {
1593 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1594 }
1595
Christopher Tatec7b31e32009-06-10 15:49:30 -07001596 // !!! TODO: get the dirs from the transport
1597 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001598 File newStateName = new File(mStateDir, packageName + ".new");
1599 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001600
Dan Egnorbb9001c2009-07-27 12:20:13 -07001601 ParcelFileDescriptor backupData = null;
1602 ParcelFileDescriptor newState = null;
1603
1604 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001605 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 backupData = ParcelFileDescriptor.open(backupDataName,
1607 ParcelFileDescriptor.MODE_READ_WRITE |
1608 ParcelFileDescriptor.MODE_CREATE |
1609 ParcelFileDescriptor.MODE_TRUNCATE);
1610
Dan Egnor01445162009-09-21 17:04:05 -07001611 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001612 Log.e(TAG, "Error getting restore data for " + packageName);
1613 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1614 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001615 }
1616
1617 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001618 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001619 backupData = ParcelFileDescriptor.open(backupDataName,
1620 ParcelFileDescriptor.MODE_READ_ONLY);
1621
Dan Egnorbb9001c2009-07-27 12:20:13 -07001622 newState = ParcelFileDescriptor.open(newStateName,
1623 ParcelFileDescriptor.MODE_READ_WRITE |
1624 ParcelFileDescriptor.MODE_CREATE |
1625 ParcelFileDescriptor.MODE_TRUNCATE);
1626
1627 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001628
1629 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001630 //
1631 // !!! TODO: the restored data should be migrated on the server
1632 // side into the current dataset. In that case the new state file
1633 // we just created would reflect the data already extant in the
1634 // backend, so there'd be nothing more to do. Until that happens,
1635 // however, we need to make sure that we record the data to the
1636 // current backend dataset. (Yes, this means shipping the data over
1637 // the wire in both directions. That's bad, but consistency comes
1638 // first, then efficiency.) Once we introduce server-side data
1639 // migration to the newly-restored device's dataset, we will change
1640 // the following from a discard of the newly-written state to the
1641 // "correct" operation of renaming into the canonical state blob.
1642 newStateName.delete(); // TODO: remove; see above comment
1643 //newStateName.renameTo(savedStateName); // TODO: replace with this
1644
Dan Egnorbb9001c2009-07-27 12:20:13 -07001645 int size = (int) backupDataName.length();
1646 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001647 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001648 Log.e(TAG, "Error restoring data for " + packageName, e);
1649 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1650
Christopher Tate96733042009-07-20 14:49:13 -07001651 // If the agent fails restore, it might have put the app's data
1652 // into an incoherent state. For consistency we wipe its data
1653 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001654 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001655 } finally {
1656 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001657 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1658 try { if (newState != null) newState.close(); } catch (IOException e) {}
1659 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001660 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001661 }
1662 }
1663
Christopher Tateee0e78a2009-07-02 11:17:03 -07001664 class PerformClearThread extends Thread {
1665 IBackupTransport mTransport;
1666 PackageInfo mPackage;
1667
1668 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1669 mTransport = transport;
1670 mPackage = packageInfo;
1671 }
1672
1673 @Override
1674 public void run() {
1675 try {
1676 // Clear the on-device backup state to ensure a full backup next time
1677 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1678 File stateFile = new File(stateDir, mPackage.packageName);
1679 stateFile.delete();
1680
1681 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001682 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001683 mTransport.clearBackupData(mPackage);
1684 } catch (RemoteException e) {
1685 // can't happen; the transport is local
1686 } finally {
1687 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001688 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001689 mTransport.finishBackup();
1690 } catch (RemoteException e) {
1691 // can't happen; the transport is local
1692 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001693
1694 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001695 synchronized (mQueueLock) {
1696 mBackupOrRestoreInProgress = false;
1697 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001698 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001699 }
1700 }
1701 }
1702
Christopher Tate4cc86e12009-09-21 19:36:51 -07001703 class PerformInitializeThread extends Thread {
1704 HashSet<String> mQueue;
1705
1706 PerformInitializeThread(HashSet<String> transportNames) {
1707 mQueue = transportNames;
1708 }
1709
1710 @Override
1711 public void run() {
1712 int status;
1713 try {
1714 for (String transportName : mQueue) {
1715 IBackupTransport transport = getTransport(transportName);
1716 if (transport == null) {
1717 Log.e(TAG, "Requested init for " + transportName + " but not found");
1718 continue;
1719 }
1720
1721 status = BackupConstants.TRANSPORT_OK;
1722 File stateDir = null;
1723
1724 Log.i(TAG, "Device init on " + transport.transportDirName());
1725
1726 stateDir = new File(mBaseStateDir, transport.transportDirName());
1727
1728 status = transport.initializeDevice();
1729 if (status != BackupConstants.TRANSPORT_OK) {
1730 Log.e(TAG, "Error from initializeDevice: " + status);
1731 }
1732 if (status == BackupConstants.TRANSPORT_OK) {
1733 status = transport.finishBackup();
1734 }
1735
1736 // Okay, the wipe really happened. Clean up our local bookkeeping.
1737 if (status == BackupConstants.TRANSPORT_OK) {
1738 resetBackupState(stateDir);
1739 synchronized (mQueueLock) {
1740 recordInitPendingLocked(false, transportName);
1741 }
1742 }
1743
1744 // If this didn't work, requeue this one and try again
1745 // after a suitable interval
1746 if (status != BackupConstants.TRANSPORT_OK) {
1747 Log.i(TAG, "Device init failed");
1748 synchronized (mQueueLock) {
1749 recordInitPendingLocked(true, transportName);
1750 }
1751 // do this via another alarm to make sure of the wakelock states
1752 long delay = transport.requestBackupTime();
1753 if (DEBUG) Log.w(TAG, "init failed on "
1754 + transportName + " resched in " + delay);
1755 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1756 System.currentTimeMillis() + delay, mRunInitIntent);
1757 } else {
1758 // success!
1759 Log.i(TAG, "Device init successful");
1760 }
1761
1762 }
1763 } catch (RemoteException e) {
1764 // can't happen; the transports are local
1765 } catch (Exception e) {
1766 Log.e(TAG, "Unexpected error performing init", e);
1767 } finally {
1768 // Done; indicate that we're finished and release the wakelock
1769 synchronized (mQueueLock) {
1770 mInitInProgress = false;
1771 }
1772 mWakelock.release();
1773 }
1774 }
1775 }
1776
Christopher Tatedf01dea2009-06-09 20:45:02 -07001777
Christopher Tate487529a2009-04-29 14:03:25 -07001778 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001779
Christopher Tatea8bf8152009-04-30 11:36:21 -07001780 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001781 // Record that we need a backup pass for the caller. Since multiple callers
1782 // may share a uid, we need to note all candidates within that uid and schedule
1783 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001784 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001785
Christopher Tate63d27002009-06-16 17:16:42 -07001786 // If the caller does not hold the BACKUP permission, it can only request a
1787 // backup of its own data.
1788 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001789 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001790 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1791 targets = mBackupParticipants.get(Binder.getCallingUid());
1792 } else {
1793 // a caller with full permission can ask to back up any participating app
1794 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001795 targets = new HashSet<ApplicationInfo>();
1796 int N = mBackupParticipants.size();
1797 for (int i = 0; i < N; i++) {
1798 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1799 if (s != null) {
1800 targets.addAll(s);
1801 }
1802 }
1803 }
Christopher Tate487529a2009-04-29 14:03:25 -07001804 if (targets != null) {
1805 synchronized (mQueueLock) {
1806 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001807 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001808 // validate the caller-supplied package name against the known set of
1809 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001810 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001811 // Add the caller to the set of pending backups. If there is
1812 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001813 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001814 if (mPendingBackups.put(app, req) == null) {
1815 // Journal this request in case of crash. The put()
1816 // operation returned null when this package was not already
1817 // in the set; we want to avoid touching the disk redundantly.
1818 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001819
Christopher Tate22b60d82009-07-07 16:36:02 -07001820 if (DEBUG) {
1821 int numKeys = mPendingBackups.size();
1822 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1823 for (BackupRequest b : mPendingBackups.values()) {
1824 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1825 }
1826 }
1827 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001828 }
1829 }
Christopher Tate487529a2009-04-29 14:03:25 -07001830 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001831 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001832 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1833 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001834 }
1835 }
Christopher Tate46758122009-05-06 11:22:00 -07001836
Christopher Tatecde87f42009-06-12 12:55:53 -07001837 private void writeToJournalLocked(String str) {
1838 if (mJournalStream != null) {
1839 try {
1840 mJournalStream.writeUTF(str);
1841 } catch (IOException e) {
1842 Log.e(TAG, "Error writing to backup journal");
1843 mJournalStream = null;
1844 mJournal = null;
1845 }
1846 }
1847 }
1848
Christopher Tateee0e78a2009-07-02 11:17:03 -07001849 // Clear the given package's backup data from the current transport
1850 public void clearBackupData(String packageName) {
1851 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1852 PackageInfo info;
1853 try {
1854 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1855 } catch (NameNotFoundException e) {
1856 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1857 return;
1858 }
1859
1860 // If the caller does not hold the BACKUP permission, it can only request a
1861 // wipe of its own backed-up data.
1862 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001863 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001864 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1865 apps = mBackupParticipants.get(Binder.getCallingUid());
1866 } else {
1867 // a caller with full permission can ask to back up any participating app
1868 // !!! TODO: allow data-clear of ANY app?
1869 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1870 apps = new HashSet<ApplicationInfo>();
1871 int N = mBackupParticipants.size();
1872 for (int i = 0; i < N; i++) {
1873 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1874 if (s != null) {
1875 apps.addAll(s);
1876 }
1877 }
1878 }
1879
1880 // now find the given package in the set of candidate apps
1881 for (ApplicationInfo app : apps) {
1882 if (app.packageName.equals(packageName)) {
1883 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1884 // found it; fire off the clear request
1885 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001886 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001887 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001888 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1889 new ClearParams(getTransport(mCurrentTransport), info));
1890 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001891 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001892 }
1893 break;
1894 }
1895 }
1896 }
1897
Christopher Tateace7f092009-06-15 18:07:25 -07001898 // Run a backup pass immediately for any applications that have declared
1899 // that they have pending updates.
1900 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001901 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001902
Christopher Tateace7f092009-06-15 18:07:25 -07001903 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001904 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001905 // Because the alarms we are using can jitter, and we want an *immediate*
1906 // backup pass to happen, we restart the timer beginning with "next time,"
1907 // then manually fire the backup trigger intent ourselves.
1908 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001909 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001910 mRunBackupIntent.send();
1911 } catch (PendingIntent.CanceledException e) {
1912 // should never happen
1913 Log.e(TAG, "run-backup intent cancelled!");
1914 }
Christopher Tate46758122009-05-06 11:22:00 -07001915 }
1916 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001917
Christopher Tate8031a3d2009-07-06 16:36:05 -07001918 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001919 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1921 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001922
Christopher Tate4cc86e12009-09-21 19:36:51 -07001923 Log.i(TAG, "Backup enabled => " + enable);
1924
Christopher Tate6ef58a12009-06-29 14:56:28 -07001925 boolean wasEnabled = mEnabled;
1926 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001927 Settings.Secure.putInt(mContext.getContentResolver(),
1928 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001929 mEnabled = enable;
1930 }
1931
Christopher Tate49401dd2009-07-01 12:34:29 -07001932 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001933 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001934 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001935 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001936 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001937 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001938 if (DEBUG) Log.i(TAG, "Opting out of backup");
1939
Christopher Tateb6787f22009-07-02 17:40:45 -07001940 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001941
1942 // This also constitutes an opt-out, so we wipe any data for
1943 // this device from the backend. We start that process with
1944 // an alarm in order to guarantee wakelock states.
1945 if (wasEnabled && mProvisioned) {
1946 // NOTE: we currently flush every registered transport, not just
1947 // the currently-active one.
1948 HashSet<String> allTransports;
1949 synchronized (mTransports) {
1950 allTransports = new HashSet<String>(mTransports.keySet());
1951 }
1952 // build the set of transports for which we are posting an init
1953 for (String transport : allTransports) {
1954 recordInitPendingLocked(true, transport);
1955 }
1956 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1957 mRunInitIntent);
1958 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001959 }
1960 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001961 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001962
Christopher Tate8031a3d2009-07-06 16:36:05 -07001963 // Mark the backup service as having been provisioned
1964 public void setBackupProvisioned(boolean available) {
1965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1966 "setBackupProvisioned");
1967
1968 boolean wasProvisioned = mProvisioned;
1969 synchronized (this) {
1970 Settings.Secure.putInt(mContext.getContentResolver(),
1971 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1972 mProvisioned = available;
1973 }
1974
1975 synchronized (mQueueLock) {
1976 if (available && !wasProvisioned && mEnabled) {
1977 // we're now good to go, so start the backup alarms
1978 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1979 } else if (!available) {
1980 // No longer enabled, so stop running backups
1981 Log.w(TAG, "Backup service no longer provisioned");
1982 mAlarmManager.cancel(mRunBackupIntent);
1983 }
1984 }
1985 }
1986
1987 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1988 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1989 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1990 BACKUP_INTERVAL, mRunBackupIntent);
1991 }
1992
Christopher Tate6ef58a12009-06-29 14:56:28 -07001993 // Report whether the backup mechanism is currently enabled
1994 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001996 return mEnabled; // no need to synchronize just to read it
1997 }
1998
Christopher Tate91717492009-06-26 21:07:13 -07001999 // Report the name of the currently active transport
2000 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002002 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002003 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002004 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002005 }
2006
Christopher Tate91717492009-06-26 21:07:13 -07002007 // Report all known, available backup transports
2008 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002009 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002010
Christopher Tate91717492009-06-26 21:07:13 -07002011 String[] list = null;
2012 ArrayList<String> known = new ArrayList<String>();
2013 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2014 if (entry.getValue() != null) {
2015 known.add(entry.getKey());
2016 }
2017 }
2018
2019 if (known.size() > 0) {
2020 list = new String[known.size()];
2021 known.toArray(list);
2022 }
2023 return list;
2024 }
2025
2026 // Select which transport to use for the next backup operation. If the given
2027 // name is not one of the available transports, no action is taken and the method
2028 // returns null.
2029 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002031
2032 synchronized (mTransports) {
2033 String prevTransport = null;
2034 if (mTransports.get(transport) != null) {
2035 prevTransport = mCurrentTransport;
2036 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002037 Settings.Secure.putString(mContext.getContentResolver(),
2038 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002039 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2040 + " returning " + prevTransport);
2041 } else {
2042 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2043 }
2044 return prevTransport;
2045 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002046 }
2047
2048 // Callback: a requested backup agent has been instantiated. This should only
2049 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002050 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002051 synchronized(mAgentConnectLock) {
2052 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2053 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2054 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2055 mConnectedAgent = agent;
2056 mConnecting = false;
2057 } else {
2058 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2059 + " claiming agent connected");
2060 }
2061 mAgentConnectLock.notifyAll();
2062 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002063 }
2064
2065 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2066 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002067 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002068 public void agentDisconnected(String packageName) {
2069 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002070 synchronized(mAgentConnectLock) {
2071 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2072 mConnectedAgent = null;
2073 mConnecting = false;
2074 } else {
2075 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2076 + " claiming agent disconnected");
2077 }
2078 mAgentConnectLock.notifyAll();
2079 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002080 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002081
Christopher Tate8c850b72009-06-07 19:33:20 -07002082 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002083 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002084 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002085
2086 synchronized(this) {
2087 if (mActiveRestoreSession != null) {
2088 Log.d(TAG, "Restore session requested but one already active");
2089 return null;
2090 }
Christopher Tate91717492009-06-26 21:07:13 -07002091 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002092 }
2093 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002094 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002095
Christopher Tate9b3905c2009-06-08 15:24:01 -07002096 // ----- Restore session -----
2097
2098 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002099 private static final String TAG = "RestoreSession";
2100
Christopher Tate9b3905c2009-06-08 15:24:01 -07002101 private IBackupTransport mRestoreTransport = null;
2102 RestoreSet[] mRestoreSets = null;
2103
Christopher Tate91717492009-06-26 21:07:13 -07002104 RestoreSession(String transport) {
2105 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002106 }
2107
2108 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002109 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002111 "getAvailableRestoreSets");
2112
Christopher Tatef68eb502009-06-16 11:02:01 -07002113 try {
Christopher Tate43383042009-07-13 15:17:13 -07002114 if (mRestoreTransport == null) {
2115 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002116 return null;
2117 }
2118 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002119 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002120 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002121 }
2122 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002123 } catch (Exception e) {
2124 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2125 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002126 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002127 }
2128
Dan Egnor0084da52009-07-29 12:57:16 -07002129 public synchronized int performRestore(long token, IRestoreObserver observer) {
2130 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2131 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002132
Christopher Tatef2c321a2009-08-10 15:43:36 -07002133 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2134 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002135
Dan Egnor0084da52009-07-29 12:57:16 -07002136 if (mRestoreTransport == null || mRestoreSets == null) {
2137 Log.e(TAG, "Ignoring performRestore() with no restore set");
2138 return -1;
2139 }
2140
Christopher Tate21ab6a52009-09-24 18:01:46 -07002141 synchronized (mQueueLock) {
2142 if (mBackupOrRestoreInProgress) {
2143 Log.e(TAG, "Backup pass in progress, restore aborted");
2144 return -1;
2145 }
2146
2147 for (int i = 0; i < mRestoreSets.length; i++) {
2148 if (token == mRestoreSets[i].token) {
2149 long oldId = Binder.clearCallingIdentity();
2150 // Suppress backups until the restore operation is finished
2151 mBackupOrRestoreInProgress = true;
2152 mWakelock.acquire();
2153 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2154 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2155 mBackupHandler.sendMessage(msg);
2156 Binder.restoreCallingIdentity(oldId);
2157 return 0;
2158 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002159 }
2160 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002161
2162 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002163 return -1;
2164 }
2165
Dan Egnor0084da52009-07-29 12:57:16 -07002166 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002167 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002168 "endRestoreSession");
2169
Dan Egnor0084da52009-07-29 12:57:16 -07002170 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002171
Dan Egnor0084da52009-07-29 12:57:16 -07002172 synchronized (this) {
2173 try {
2174 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2175 } catch (Exception e) {
2176 Log.e(TAG, "Error in finishRestore", e);
2177 } finally {
2178 mRestoreTransport = null;
2179 }
2180 }
2181
2182 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002183 if (BackupManagerService.this.mActiveRestoreSession == this) {
2184 BackupManagerService.this.mActiveRestoreSession = null;
2185 } else {
2186 Log.e(TAG, "ending non-current restore session");
2187 }
2188 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002189 }
2190 }
2191
Christopher Tate043dadc2009-06-02 16:11:00 -07002192
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002193 @Override
2194 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2195 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002196 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
2197 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07002198 pw.println("Available transports:");
2199 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002200 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
2201 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07002202 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002203 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07002204 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002205 for (int i=0; i<N; i++) {
2206 int uid = mBackupParticipants.keyAt(i);
2207 pw.print(" uid: ");
2208 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002209 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2210 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002211 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002212 }
2213 }
Christopher Tate73e02522009-07-15 14:18:26 -07002214 pw.println("Ever backed up: " + mEverStoredApps.size());
2215 for (String pkg : mEverStoredApps) {
2216 pw.println(" " + pkg);
2217 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07002218 pw.println("Pending: " + mPendingBackups.size());
2219 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002220 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002221 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002222 }
2223 }
Christopher Tate487529a2009-04-29 14:03:25 -07002224}