blob: cb917db9e88d312274f62f27b0dec1e745397540 [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 Tateb6787f22009-07-02 17:40:45 -0700640 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700641 break;
642 }
643
Joe Onorato8ad02812009-05-13 01:41:44 -0400644 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700645 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700646 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400647 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700648 // Do we have any work to do?
649 if (mPendingBackups.size() > 0) {
650 for (BackupRequest b: mPendingBackups.values()) {
651 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700652 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700653 Log.v(TAG, "clearing pending backups");
654 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700655
Christopher Tate49401dd2009-07-01 12:34:29 -0700656 // Start a new backup-queue journal file too
657 if (mJournalStream != null) {
658 try {
659 mJournalStream.close();
660 } catch (IOException e) {
661 // don't need to do anything
662 }
663 makeJournalLocked();
664 }
665
666 // At this point, we have started a new journal file, and the old
667 // file identity is being passed to the backup processing thread.
668 // When it completes successfully, that old journal file will be
669 // deleted. If we crash prior to that, the old journal is parsed
670 // at next boot and the journaled requests fulfilled.
671 (new PerformBackupThread(transport, queue, oldJournal)).start();
672 } else {
673 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700674 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700675 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400676 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700677 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700678 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700679
680 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400681 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700682
683 case MSG_RUN_RESTORE:
684 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700685 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400686 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700687 (new PerformRestoreThread(params.transport, params.observer,
688 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700689 break;
690 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700691
692 case MSG_RUN_CLEAR:
693 {
694 ClearParams params = (ClearParams)msg.obj;
695 (new PerformClearThread(params.transport, params.packageInfo)).start();
696 break;
697 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700698
699 case MSG_RUN_INITIALIZE:
700 {
701 HashSet<String> queue;
702
703 // Snapshot the pending-init queue and work on that
704 synchronized (mQueueLock) {
705 queue = new HashSet<String>(mPendingInits);
706 mPendingInits.clear();
707 }
708
709 (new PerformInitializeThread(queue)).start();
710 break;
711 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400712 }
713 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400714 }
715
Christopher Tate181fafa2009-05-14 11:12:14 -0700716 // Add the backup agents in the given package to our set of known backup participants.
717 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700718 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700719 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700720 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700721 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700722 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700723 }
724
Christopher Tate181fafa2009-05-14 11:12:14 -0700725 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700726 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700727 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700728 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
729 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700730 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700731 + " uid=" + p.applicationInfo.uid
732 + " killAfterRestore="
733 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
734 + " restoreNeedsApplication="
735 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
736 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700737 }
738 }
739
Dan Egnorefe52642009-06-24 00:16:33 -0700740 for (PackageInfo pkg : targetPkgs) {
741 if (packageName == null || pkg.packageName.equals(packageName)) {
742 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700743 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700744 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700745 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700746 mBackupParticipants.put(uid, set);
747 }
Dan Egnorefe52642009-06-24 00:16:33 -0700748 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700749
750 // If we've never seen this app before, schedule a backup for it
751 if (!mEverStoredApps.contains(pkg.packageName)) {
752 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
753 + " never backed up; scheduling");
754 try {
755 dataChanged(pkg.packageName);
756 } catch (RemoteException e) {
757 // can't happen; it's a local method call
758 }
759 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700760 }
Christopher Tate487529a2009-04-29 14:03:25 -0700761 }
762 }
763
Christopher Tate6785dd82009-06-18 15:58:25 -0700764 // Remove the given package's entry from our known active set. If
765 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700766 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700767 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700768 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700769 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700770 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700771 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700772 int flags = PackageManager.GET_SIGNATURES;
773 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700774 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700775 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700776 }
777 } else {
778 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700779 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700780 }
781 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700782 }
783
Joe Onorato8ad02812009-05-13 01:41:44 -0400784 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700785 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700786 if (DEBUG) {
787 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
788 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700789 for (PackageInfo p : agents) {
790 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700791 }
792 }
Dan Egnorefe52642009-06-24 00:16:33 -0700793 for (PackageInfo pkg : agents) {
794 if (packageName == null || pkg.packageName.equals(packageName)) {
795 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700796 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700797 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700798 // Find the existing entry with the same package name, and remove it.
799 // We can't just remove(app) because the instances are different.
800 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700801 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700802 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700803 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700804 break;
805 }
806 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700807 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700808 mBackupParticipants.delete(uid);
809 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700810 }
811 }
812 }
813 }
814
Christopher Tate181fafa2009-05-14 11:12:14 -0700815 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700816 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700817 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700818 int flags = PackageManager.GET_SIGNATURES;
819 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
820 int N = packages.size();
821 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700822 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700823 try {
824 ApplicationInfo app = pkg.applicationInfo;
825 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
826 || app.backupAgentName == null
827 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
828 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
829 packages.remove(a);
830 }
831 else {
832 // we will need the shared library path, so look that up and store it here
833 app = mPackageManager.getApplicationInfo(pkg.packageName,
834 PackageManager.GET_SHARED_LIBRARY_FILES);
835 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
836 }
837 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700838 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700839 }
840 }
Dan Egnorefe52642009-06-24 00:16:33 -0700841 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700842 }
Christopher Tateaa088442009-06-16 18:25:46 -0700843
Christopher Tate3799bc22009-05-06 16:13:56 -0700844 // Reset the given package's known backup participants. Unlike add/remove, the update
845 // action cannot be passed a null package name.
846 void updatePackageParticipantsLocked(String packageName) {
847 if (packageName == null) {
848 Log.e(TAG, "updatePackageParticipants called with null package name");
849 return;
850 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700851 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700852
853 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700854 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700855 removePackageParticipantsLockedInner(packageName, allApps);
856 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700857 }
858
Christopher Tate73e02522009-07-15 14:18:26 -0700859 // Called from the backup thread: record that the given app has been successfully
860 // backed up at least once
861 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700862 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700863 synchronized (mEverStoredApps) {
864 if (mEverStoredApps.add(packageName)) {
865 try {
866 mEverStoredStream.writeUTF(packageName);
867 } catch (IOException e) {
868 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
869 try {
870 mEverStoredStream.close();
871 } catch (IOException ioe) {
872 // we're dropping it; no need to handle an exception on close here
873 }
874 mEverStoredStream = null;
875 }
876 }
877 }
878 }
879 }
880
Christopher Tatee97e8072009-07-15 16:45:50 -0700881 // Remove our awareness of having ever backed up the given package
882 void removeEverBackedUp(String packageName) {
883 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
884 + ", new set:");
885
886 if (mEverStoredStream != null) {
887 synchronized (mEverStoredApps) {
888 // Rewrite the file and rename to overwrite. If we reboot in the middle,
889 // we'll recognize on initialization time that the package no longer
890 // exists and fix it up then.
891 File tempKnownFile = new File(mBaseStateDir, "processed.new");
892 try {
893 mEverStoredStream.close();
894 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
895 mEverStoredApps.remove(packageName);
896 for (String s : mEverStoredApps) {
897 known.writeUTF(s);
898 if (DEBUG) Log.v(TAG, " " + s);
899 }
900 known.close();
901 tempKnownFile.renameTo(mEverStored);
902 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
903 } catch (IOException e) {
904 // Bad: we couldn't create the new copy. For safety's sake we
905 // abandon the whole process and remove all what's-backed-up
906 // state entirely, meaning we'll force a backup pass for every
907 // participant on the next boot or [re]install.
908 Log.w(TAG, "Error rewriting backed-up set; halting log");
909 mEverStoredStream = null;
910 mEverStoredApps.clear();
911 tempKnownFile.delete();
912 mEverStored.delete();
913 }
914 }
915 }
916 }
917
Dan Egnor87a02bc2009-06-17 02:30:10 -0700918 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700919 private IBackupTransport getTransport(String transportName) {
920 synchronized (mTransports) {
921 IBackupTransport transport = mTransports.get(transportName);
922 if (transport == null) {
923 Log.w(TAG, "Requested unavailable transport: " + transportName);
924 }
925 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700926 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700927 }
928
Christopher Tatedf01dea2009-06-09 20:45:02 -0700929 // fire off a backup agent, blocking until it attaches or times out
930 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
931 IBackupAgent agent = null;
932 synchronized(mAgentConnectLock) {
933 mConnecting = true;
934 mConnectedAgent = null;
935 try {
936 if (mActivityManager.bindBackupAgent(app, mode)) {
937 Log.d(TAG, "awaiting agent for " + app);
938
939 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700940 // only wait 10 seconds for the clear data to happen
941 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
942 while (mConnecting && mConnectedAgent == null
943 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700944 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700945 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700946 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700947 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700948 return null;
949 }
950 }
951
952 // if we timed out with no connect, abort and move on
953 if (mConnecting == true) {
954 Log.w(TAG, "Timeout waiting for agent " + app);
955 return null;
956 }
957 agent = mConnectedAgent;
958 }
959 } catch (RemoteException e) {
960 // can't happen
961 }
962 }
963 return agent;
964 }
965
Christopher Tatec7b31e32009-06-10 15:49:30 -0700966 // clear an application's data, blocking until the operation completes or times out
967 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700968 // Don't wipe packages marked allowClearUserData=false
969 try {
970 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
971 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
972 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
973 + packageName);
974 return;
975 }
976 } catch (NameNotFoundException e) {
977 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
978 return;
979 }
980
Christopher Tatec7b31e32009-06-10 15:49:30 -0700981 ClearDataObserver observer = new ClearDataObserver();
982
983 synchronized(mClearDataLock) {
984 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700985 /* This is causing some critical processes to be killed during setup.
986 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700987 try {
988 mActivityManager.clearApplicationUserData(packageName, observer);
989 } catch (RemoteException e) {
990 // can't happen because the activity manager is in this process
991 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700992 */
993 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700994
995 // only wait 10 seconds for the clear data to happen
996 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
997 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
998 try {
999 mClearDataLock.wait(5000);
1000 } catch (InterruptedException e) {
1001 // won't happen, but still.
1002 mClearingData = false;
1003 }
1004 }
1005 }
1006 }
1007
1008 class ClearDataObserver extends IPackageDataObserver.Stub {
1009 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -07001010 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001011 synchronized(mClearDataLock) {
1012 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001013 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001014 }
1015 }
1016 }
1017
Christopher Tate043dadc2009-06-02 16:11:00 -07001018 // ----- Back up a set of applications via a worker thread -----
1019
1020 class PerformBackupThread extends Thread {
1021 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001022 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001023 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001024 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001025 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001026
Christopher Tateaa088442009-06-16 18:25:46 -07001027 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001028 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001029 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001030 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001031 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001032
1033 try {
1034 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1035 } catch (RemoteException e) {
1036 // can't happen; the transport is local
1037 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001038 }
1039
1040 @Override
1041 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001042 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001043 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001044 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1045
Christopher Tate79588342009-06-30 16:11:49 -07001046 // Backups run at background priority
1047 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1048
Christopher Tate043dadc2009-06-02 16:11:00 -07001049 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001050 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001051
1052 // If we haven't stored anything yet, we need to do an init operation.
1053 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
1054 status = mTransport.initializeDevice();
1055 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001056
1057 // The package manager doesn't have a proper <application> etc, but since
1058 // it's running here in the system process we can just set up its agent
1059 // directly and use a synthetic BackupRequest. We always run this pass
1060 // because it's cheap and this way we guarantee that we don't get out of
1061 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001062 if (status == BackupConstants.TRANSPORT_OK) {
1063 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1064 mPackageManager, allAgentPackages());
1065 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1066 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1067 status = processOneBackup(pmRequest,
1068 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1069 }
Christopher Tate90967f42009-09-20 15:28:33 -07001070
Dan Egnor01445162009-09-21 17:04:05 -07001071 if (status == BackupConstants.TRANSPORT_OK) {
1072 // Now run all the backups in our queue
1073 status = doQueuedBackups(mTransport);
1074 }
1075
1076 if (status == BackupConstants.TRANSPORT_OK) {
1077 // Tell the transport to finish everything it has buffered
1078 status = mTransport.finishBackup();
1079 if (status == BackupConstants.TRANSPORT_OK) {
1080 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1081 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1082 } else {
1083 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
1084 Log.e(TAG, "Transport error in finishBackup()");
1085 }
1086 }
1087
Dan Egnor01445162009-09-21 17:04:05 -07001088 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001089 // The backend reports that our dataset has been wiped. We need to
1090 // reset all of our bookkeeping and instead run a new backup pass for
1091 // everything.
1092 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1093 resetBackupState(mStateDir);
1094 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001095 }
1096 } catch (Exception e) {
1097 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001098 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001099 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001100 // If things went wrong, we need to re-stage the apps we had expected
1101 // to be backing up in this pass. This journals the package names in
1102 // the current active pending-backup file, not in the we are holding
1103 // here in mJournal.
1104 if (status != BackupConstants.TRANSPORT_OK) {
1105 Log.w(TAG, "Backup pass unsuccessful, restaging");
1106 for (BackupRequest req : mQueue) {
1107 try {
1108 dataChanged(req.appInfo.packageName);
1109 } catch (RemoteException e) {
1110 // can't happen; it's a local call
1111 }
1112 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001113
1114 // We also want to reset the backup schedule based on whatever
1115 // the transport suggests by way of retry/backoff time.
1116 try {
1117 startBackupAlarmsLocked(mTransport.requestBackupTime());
1118 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001119 }
1120
1121 // Either backup was successful, in which case we of course do not need
1122 // this pass's journal any more; or it failed, in which case we just
1123 // re-enqueued all of these packages in the current active journal.
1124 // Either way, we no longer need this pass's journal.
1125 if (!mJournal.delete()) {
1126 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1127 }
1128
Christopher Tate21ab6a52009-09-24 18:01:46 -07001129 // Only once we're entirely finished do we indicate our completion
1130 // and release the wakelock
1131 synchronized (mQueueLock) {
1132 mBackupOrRestoreInProgress = false;
1133 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001134 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001135 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001136 }
1137
Dan Egnor01445162009-09-21 17:04:05 -07001138 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001139 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001140 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001141
Christopher Tate0749dcd2009-08-13 15:13:03 -07001142 // Don't run backup, even if requested, if the target app does not have
1143 // the requisite permission
1144 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1145 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1146 Log.w(TAG, "Skipping backup of unprivileged package "
1147 + request.appInfo.packageName);
1148 continue;
1149 }
1150
Christopher Tate043dadc2009-06-02 16:11:00 -07001151 IBackupAgent agent = null;
1152 int mode = (request.fullBackup)
1153 ? IApplicationThread.BACKUP_MODE_FULL
1154 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1155 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001156 agent = bindToAgentSynchronous(request.appInfo, mode);
1157 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001158 int result = processOneBackup(request, agent, transport);
1159 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001160 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001161 } catch (SecurityException ex) {
1162 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001163 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001164 } finally {
1165 try { // unbind even on timeout, just in case
1166 mActivityManager.unbindBackupAgent(request.appInfo);
1167 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001168 }
1169 }
Dan Egnor01445162009-09-21 17:04:05 -07001170
1171 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001172 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001173
Dan Egnor01445162009-09-21 17:04:05 -07001174 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1175 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001176 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001177 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001178
Dan Egnorbb9001c2009-07-27 12:20:13 -07001179 File savedStateName = new File(mStateDir, packageName);
1180 File backupDataName = new File(mDataDir, packageName + ".data");
1181 File newStateName = new File(mStateDir, packageName + ".new");
1182
1183 ParcelFileDescriptor savedState = null;
1184 ParcelFileDescriptor backupData = null;
1185 ParcelFileDescriptor newState = null;
1186
1187 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001188 try {
1189 // Look up the package info & signatures. This is first so that if it
1190 // throws an exception, there's no file setup yet that would need to
1191 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001192 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1193 // The metadata 'package' is synthetic
1194 packInfo = new PackageInfo();
1195 packInfo.packageName = packageName;
1196 } else {
1197 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001198 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001199 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001200
Christopher Tatec7b31e32009-06-10 15:49:30 -07001201 // In a full backup, we pass a null ParcelFileDescriptor as
1202 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001203 if (!request.fullBackup) {
1204 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001205 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001206 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1207 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001208
Dan Egnorbb9001c2009-07-27 12:20:13 -07001209 backupData = ParcelFileDescriptor.open(backupDataName,
1210 ParcelFileDescriptor.MODE_READ_WRITE |
1211 ParcelFileDescriptor.MODE_CREATE |
1212 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001213
Dan Egnorbb9001c2009-07-27 12:20:13 -07001214 newState = ParcelFileDescriptor.open(newStateName,
1215 ParcelFileDescriptor.MODE_READ_WRITE |
1216 ParcelFileDescriptor.MODE_CREATE |
1217 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001218
1219 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001220 agent.doBackup(savedState, backupData, newState);
1221 logBackupComplete(packageName);
1222 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001223 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001224 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001225 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1226 backupDataName.delete();
1227 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001228 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001229 } finally {
1230 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1231 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1232 try { if (newState != null) newState.close(); } catch (IOException e) {}
1233 savedState = backupData = newState = null;
1234 }
1235
1236 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001237 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001238 try {
1239 int size = (int) backupDataName.length();
1240 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001241 if (result == BackupConstants.TRANSPORT_OK) {
1242 backupData = ParcelFileDescriptor.open(backupDataName,
1243 ParcelFileDescriptor.MODE_READ_ONLY);
1244 result = transport.performBackup(packInfo, backupData);
1245 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001246
Dan Egnor83861e72009-09-17 16:17:55 -07001247 // TODO - We call finishBackup() for each application backed up, because
1248 // we need to know now whether it succeeded or failed. Instead, we should
1249 // hold off on finishBackup() until the end, which implies holding off on
1250 // renaming *all* the output state files (see below) until that happens.
1251
Dan Egnor01445162009-09-21 17:04:05 -07001252 if (result == BackupConstants.TRANSPORT_OK) {
1253 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001254 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255 } else {
1256 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1257 }
1258
1259 // After successful transport, delete the now-stale data
1260 // and juggle the files so that next time we supply the agent
1261 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001262 if (result == BackupConstants.TRANSPORT_OK) {
1263 backupDataName.delete();
1264 newStateName.renameTo(savedStateName);
1265 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1266 } else {
1267 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1268 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001269 } catch (Exception e) {
1270 Log.e(TAG, "Transport error backing up " + packageName, e);
1271 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001272 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001273 } finally {
1274 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001275 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001276
Dan Egnor01445162009-09-21 17:04:05 -07001277 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001278 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001279 }
1280
Christopher Tatedf01dea2009-06-09 20:45:02 -07001281
1282 // ----- Restore handling -----
1283
Christopher Tateabce4e82009-06-18 18:35:32 -07001284 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001285 // Allow unsigned apps, but not signed on one device and unsigned on the other
1286 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001287 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1288 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001289 if ((storedSigs == null || storedSigs.length == 0)
1290 && (deviceSigs == null || deviceSigs.length == 0)) {
1291 return true;
1292 }
1293 if (storedSigs == null || deviceSigs == null) {
1294 return false;
1295 }
1296
Christopher Tateabce4e82009-06-18 18:35:32 -07001297 // !!! TODO: this demands that every stored signature match one
1298 // that is present on device, and does not demand the converse.
1299 // Is this this right policy?
1300 int nStored = storedSigs.length;
1301 int nDevice = deviceSigs.length;
1302
1303 for (int i=0; i < nStored; i++) {
1304 boolean match = false;
1305 for (int j=0; j < nDevice; j++) {
1306 if (storedSigs[i].equals(deviceSigs[j])) {
1307 match = true;
1308 break;
1309 }
1310 }
1311 if (!match) {
1312 return false;
1313 }
1314 }
1315 return true;
1316 }
1317
Christopher Tatedf01dea2009-06-09 20:45:02 -07001318 class PerformRestoreThread extends Thread {
1319 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001320 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001321 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001322 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001323
Christopher Tate5cbbf562009-06-22 16:44:51 -07001324 class RestoreRequest {
1325 public PackageInfo app;
1326 public int storedAppVersion;
1327
1328 RestoreRequest(PackageInfo _app, int _version) {
1329 app = _app;
1330 storedAppVersion = _version;
1331 }
1332 }
1333
Christopher Tate7d562ec2009-06-25 18:03:43 -07001334 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001335 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001336 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001337 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001338 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001339 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001340
1341 try {
1342 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1343 } catch (RemoteException e) {
1344 // can't happen; the transport is local
1345 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001346 }
1347
1348 @Override
1349 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001350 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001351 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001352 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001353 /**
1354 * Restore sequence:
1355 *
Dan Egnorefe52642009-06-24 00:16:33 -07001356 * 1. get the restore set description for our identity
1357 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001358 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001359 * 3. for each app in the restore queue:
1360 * 3.a. clear the app data
1361 * 3.b. get the restore data for the app from the transport
1362 * 3.c. launch the backup agent for the app
1363 * 3.d. agent.doRestore() with the data from the server
1364 * 3.e. unbind the agent [and kill the app?]
1365 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001366 *
1367 * On errors, we try our best to recover and move on to the next
1368 * application, but if necessary we abort the whole operation --
1369 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001370 */
1371
Christopher Tate7d562ec2009-06-25 18:03:43 -07001372 int error = -1; // assume error
1373
Dan Egnorefe52642009-06-24 00:16:33 -07001374 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001375 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001376 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001377 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001378
Dan Egnorefe52642009-06-24 00:16:33 -07001379 // Get the list of all packages which have backup enabled.
1380 // (Include the Package Manager metadata pseudo-package first.)
1381 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1382 PackageInfo omPackage = new PackageInfo();
1383 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1384 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001385
Dan Egnorefe52642009-06-24 00:16:33 -07001386 List<PackageInfo> agentPackages = allAgentPackages();
1387 restorePackages.addAll(agentPackages);
1388
Christopher Tate7d562ec2009-06-25 18:03:43 -07001389 // let the observer know that we're running
1390 if (mObserver != null) {
1391 try {
1392 // !!! TODO: get an actual count from the transport after
1393 // its startRestore() runs?
1394 mObserver.restoreStarting(restorePackages.size());
1395 } catch (RemoteException e) {
1396 Log.d(TAG, "Restore observer died at restoreStarting");
1397 mObserver = null;
1398 }
1399 }
1400
Dan Egnor01445162009-09-21 17:04:05 -07001401 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1402 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001403 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001404 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001405 return;
1406 }
1407
1408 String packageName = mTransport.nextRestorePackage();
1409 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001410 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001411 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001412 return;
1413 } else if (packageName.equals("")) {
1414 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001415 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1416 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001417 return;
1418 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1419 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1420 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1422 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001423 return;
1424 }
1425
1426 // Pull the Package Manager metadata from the restore set first
1427 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1428 mPackageManager, agentPackages);
1429 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1430
Christopher Tate8c032472009-07-02 14:28:47 -07001431 // Verify that the backup set includes metadata. If not, we can't do
1432 // signature/version verification etc, so we simply do not proceed with
1433 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001434 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001435 Log.e(TAG, "No restore metadata available, so not restoring settings");
1436 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1437 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001438 return;
1439 }
1440
Christopher Tate7d562ec2009-06-25 18:03:43 -07001441 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001442 for (;;) {
1443 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001444
Dan Egnorefe52642009-06-24 00:16:33 -07001445 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001446 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001447 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001448 return;
1449 } else if (packageName.equals("")) {
1450 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001451 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001452
Christopher Tate7d562ec2009-06-25 18:03:43 -07001453 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001454 try {
1455 mObserver.onUpdate(count);
1456 } catch (RemoteException e) {
1457 Log.d(TAG, "Restore observer died in onUpdate");
1458 mObserver = null;
1459 }
1460 }
1461
Dan Egnorefe52642009-06-24 00:16:33 -07001462 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1463 if (metaInfo == null) {
1464 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001465 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1466 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001467 continue;
1468 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001469
Dan Egnorbb9001c2009-07-27 12:20:13 -07001470 PackageInfo packageInfo;
1471 try {
1472 int flags = PackageManager.GET_SIGNATURES;
1473 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1474 } catch (NameNotFoundException e) {
1475 Log.e(TAG, "Invalid package restoring data", e);
1476 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1477 "Package missing on device");
1478 continue;
1479 }
1480
Dan Egnorefe52642009-06-24 00:16:33 -07001481 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001482 String message = "Version " + metaInfo.versionCode
1483 + " > installed version " + packageInfo.versionCode;
1484 Log.w(TAG, "Package " + packageName + ": " + message);
1485 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001486 continue;
1487 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001488
Dan Egnorefe52642009-06-24 00:16:33 -07001489 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1490 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001491 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1492 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001493 continue;
1494 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001495
Dan Egnorefe52642009-06-24 00:16:33 -07001496 if (DEBUG) Log.v(TAG, "Package " + packageName
1497 + " restore version [" + metaInfo.versionCode
1498 + "] is compatible with installed version ["
1499 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001500
Christopher Tate5e1ab332009-09-01 20:32:49 -07001501 // Now perform the actual restore: first clear the app's data
1502 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001503 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001504
1505 // Then set up and bind the agent (with a restricted Application object
1506 // unless the application says otherwise)
1507 boolean useRealApp = (packageInfo.applicationInfo.flags
1508 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1509 if (DEBUG && useRealApp) {
1510 Log.v(TAG, "agent requires real Application subclass for restore");
1511 }
Dan Egnorefe52642009-06-24 00:16:33 -07001512 IBackupAgent agent = bindToAgentSynchronous(
1513 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001514 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1515 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001516 if (agent == null) {
1517 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001518 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1519 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001520 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001521 }
1522
Christopher Tate5e1ab332009-09-01 20:32:49 -07001523 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001524 try {
1525 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001526 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001527 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001528 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001529 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001530
1531 // The agent was probably running with a stub Application object,
1532 // which isn't a valid run mode for the main app logic. Shut
1533 // down the app so that next time it's launched, it gets the
1534 // usual full initialization.
1535 if ((packageInfo.applicationInfo.flags
1536 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1537 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1538 + packageInfo.applicationInfo.processName);
1539 mActivityManager.killApplicationProcess(
1540 packageInfo.applicationInfo.processName,
1541 packageInfo.applicationInfo.uid);
1542 }
Dan Egnorefe52642009-06-24 00:16:33 -07001543 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001544 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001545
1546 // if we get this far, report success to the observer
1547 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001548 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1549 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1550 } catch (Exception e) {
1551 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001552 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001553 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1554
Dan Egnorefe52642009-06-24 00:16:33 -07001555 try {
1556 mTransport.finishRestore();
1557 } catch (RemoteException e) {
1558 Log.e(TAG, "Error finishing restore", e);
1559 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001560
1561 if (mObserver != null) {
1562 try {
1563 mObserver.restoreFinished(error);
1564 } catch (RemoteException e) {
1565 Log.d(TAG, "Restore observer died at restoreFinished");
1566 }
1567 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001568
1569 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001570 synchronized (mQueueLock) {
1571 mBackupOrRestoreInProgress = false;
1572 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001573 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001574 }
1575 }
1576
Dan Egnorefe52642009-06-24 00:16:33 -07001577 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1578 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001579 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001580 final String packageName = app.packageName;
1581
Dan Egnorbb9001c2009-07-27 12:20:13 -07001582 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001583
Christopher Tate0749dcd2009-08-13 15:13:03 -07001584 // Don't restore to unprivileged packages
1585 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1586 packageName) != PackageManager.PERMISSION_GRANTED) {
1587 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1588 }
1589
Christopher Tatec7b31e32009-06-10 15:49:30 -07001590 // !!! TODO: get the dirs from the transport
1591 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001592 File newStateName = new File(mStateDir, packageName + ".new");
1593 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001594
Dan Egnorbb9001c2009-07-27 12:20:13 -07001595 ParcelFileDescriptor backupData = null;
1596 ParcelFileDescriptor newState = null;
1597
1598 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001599 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001600 backupData = ParcelFileDescriptor.open(backupDataName,
1601 ParcelFileDescriptor.MODE_READ_WRITE |
1602 ParcelFileDescriptor.MODE_CREATE |
1603 ParcelFileDescriptor.MODE_TRUNCATE);
1604
Dan Egnor01445162009-09-21 17:04:05 -07001605 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 Log.e(TAG, "Error getting restore data for " + packageName);
1607 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1608 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001609 }
1610
1611 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001612 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001613 backupData = ParcelFileDescriptor.open(backupDataName,
1614 ParcelFileDescriptor.MODE_READ_ONLY);
1615
Dan Egnorbb9001c2009-07-27 12:20:13 -07001616 newState = ParcelFileDescriptor.open(newStateName,
1617 ParcelFileDescriptor.MODE_READ_WRITE |
1618 ParcelFileDescriptor.MODE_CREATE |
1619 ParcelFileDescriptor.MODE_TRUNCATE);
1620
1621 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001622
1623 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001624 //
1625 // !!! TODO: the restored data should be migrated on the server
1626 // side into the current dataset. In that case the new state file
1627 // we just created would reflect the data already extant in the
1628 // backend, so there'd be nothing more to do. Until that happens,
1629 // however, we need to make sure that we record the data to the
1630 // current backend dataset. (Yes, this means shipping the data over
1631 // the wire in both directions. That's bad, but consistency comes
1632 // first, then efficiency.) Once we introduce server-side data
1633 // migration to the newly-restored device's dataset, we will change
1634 // the following from a discard of the newly-written state to the
1635 // "correct" operation of renaming into the canonical state blob.
1636 newStateName.delete(); // TODO: remove; see above comment
1637 //newStateName.renameTo(savedStateName); // TODO: replace with this
1638
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 int size = (int) backupDataName.length();
1640 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001641 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001642 Log.e(TAG, "Error restoring data for " + packageName, e);
1643 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1644
Christopher Tate96733042009-07-20 14:49:13 -07001645 // If the agent fails restore, it might have put the app's data
1646 // into an incoherent state. For consistency we wipe its data
1647 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001648 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001649 } finally {
1650 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001651 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1652 try { if (newState != null) newState.close(); } catch (IOException e) {}
1653 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001654 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001655 }
1656 }
1657
Christopher Tateee0e78a2009-07-02 11:17:03 -07001658 class PerformClearThread extends Thread {
1659 IBackupTransport mTransport;
1660 PackageInfo mPackage;
1661
1662 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1663 mTransport = transport;
1664 mPackage = packageInfo;
1665 }
1666
1667 @Override
1668 public void run() {
1669 try {
1670 // Clear the on-device backup state to ensure a full backup next time
1671 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1672 File stateFile = new File(stateDir, mPackage.packageName);
1673 stateFile.delete();
1674
1675 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001676 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001677 mTransport.clearBackupData(mPackage);
1678 } catch (RemoteException e) {
1679 // can't happen; the transport is local
1680 } finally {
1681 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001682 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001683 mTransport.finishBackup();
1684 } catch (RemoteException e) {
1685 // can't happen; the transport is local
1686 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001687
1688 // Last but not least, release the cpu
1689 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001690 }
1691 }
1692 }
1693
Christopher Tate4cc86e12009-09-21 19:36:51 -07001694 class PerformInitializeThread extends Thread {
1695 HashSet<String> mQueue;
1696
1697 PerformInitializeThread(HashSet<String> transportNames) {
1698 mQueue = transportNames;
1699 }
1700
1701 @Override
1702 public void run() {
1703 int status;
1704 try {
1705 for (String transportName : mQueue) {
1706 IBackupTransport transport = getTransport(transportName);
1707 if (transport == null) {
1708 Log.e(TAG, "Requested init for " + transportName + " but not found");
1709 continue;
1710 }
1711
1712 status = BackupConstants.TRANSPORT_OK;
1713 File stateDir = null;
1714
1715 Log.i(TAG, "Device init on " + transport.transportDirName());
1716
1717 stateDir = new File(mBaseStateDir, transport.transportDirName());
1718
1719 status = transport.initializeDevice();
1720 if (status != BackupConstants.TRANSPORT_OK) {
1721 Log.e(TAG, "Error from initializeDevice: " + status);
1722 }
1723 if (status == BackupConstants.TRANSPORT_OK) {
1724 status = transport.finishBackup();
1725 }
1726
1727 // Okay, the wipe really happened. Clean up our local bookkeeping.
1728 if (status == BackupConstants.TRANSPORT_OK) {
1729 resetBackupState(stateDir);
1730 synchronized (mQueueLock) {
1731 recordInitPendingLocked(false, transportName);
1732 }
1733 }
1734
1735 // If this didn't work, requeue this one and try again
1736 // after a suitable interval
1737 if (status != BackupConstants.TRANSPORT_OK) {
1738 Log.i(TAG, "Device init failed");
1739 synchronized (mQueueLock) {
1740 recordInitPendingLocked(true, transportName);
1741 }
1742 // do this via another alarm to make sure of the wakelock states
1743 long delay = transport.requestBackupTime();
1744 if (DEBUG) Log.w(TAG, "init failed on "
1745 + transportName + " resched in " + delay);
1746 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1747 System.currentTimeMillis() + delay, mRunInitIntent);
1748 } else {
1749 // success!
1750 Log.i(TAG, "Device init successful");
1751 }
1752
1753 }
1754 } catch (RemoteException e) {
1755 // can't happen; the transports are local
1756 } catch (Exception e) {
1757 Log.e(TAG, "Unexpected error performing init", e);
1758 } finally {
1759 // Done; indicate that we're finished and release the wakelock
1760 synchronized (mQueueLock) {
1761 mInitInProgress = false;
1762 }
1763 mWakelock.release();
1764 }
1765 }
1766 }
1767
Christopher Tatedf01dea2009-06-09 20:45:02 -07001768
Christopher Tate487529a2009-04-29 14:03:25 -07001769 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001770
Christopher Tatea8bf8152009-04-30 11:36:21 -07001771 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001772 // Record that we need a backup pass for the caller. Since multiple callers
1773 // may share a uid, we need to note all candidates within that uid and schedule
1774 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001775 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001776
Christopher Tate63d27002009-06-16 17:16:42 -07001777 // If the caller does not hold the BACKUP permission, it can only request a
1778 // backup of its own data.
1779 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001780 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001781 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1782 targets = mBackupParticipants.get(Binder.getCallingUid());
1783 } else {
1784 // a caller with full permission can ask to back up any participating app
1785 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001786 targets = new HashSet<ApplicationInfo>();
1787 int N = mBackupParticipants.size();
1788 for (int i = 0; i < N; i++) {
1789 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1790 if (s != null) {
1791 targets.addAll(s);
1792 }
1793 }
1794 }
Christopher Tate487529a2009-04-29 14:03:25 -07001795 if (targets != null) {
1796 synchronized (mQueueLock) {
1797 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001798 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001799 // validate the caller-supplied package name against the known set of
1800 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001801 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001802 // Add the caller to the set of pending backups. If there is
1803 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001804 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001805 if (mPendingBackups.put(app, req) == null) {
1806 // Journal this request in case of crash. The put()
1807 // operation returned null when this package was not already
1808 // in the set; we want to avoid touching the disk redundantly.
1809 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001810
Christopher Tate22b60d82009-07-07 16:36:02 -07001811 if (DEBUG) {
1812 int numKeys = mPendingBackups.size();
1813 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1814 for (BackupRequest b : mPendingBackups.values()) {
1815 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1816 }
1817 }
1818 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001819 }
1820 }
Christopher Tate487529a2009-04-29 14:03:25 -07001821 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001822 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001823 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1824 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001825 }
1826 }
Christopher Tate46758122009-05-06 11:22:00 -07001827
Christopher Tatecde87f42009-06-12 12:55:53 -07001828 private void writeToJournalLocked(String str) {
1829 if (mJournalStream != null) {
1830 try {
1831 mJournalStream.writeUTF(str);
1832 } catch (IOException e) {
1833 Log.e(TAG, "Error writing to backup journal");
1834 mJournalStream = null;
1835 mJournal = null;
1836 }
1837 }
1838 }
1839
Christopher Tateee0e78a2009-07-02 11:17:03 -07001840 // Clear the given package's backup data from the current transport
1841 public void clearBackupData(String packageName) {
1842 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1843 PackageInfo info;
1844 try {
1845 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1846 } catch (NameNotFoundException e) {
1847 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1848 return;
1849 }
1850
1851 // If the caller does not hold the BACKUP permission, it can only request a
1852 // wipe of its own backed-up data.
1853 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001854 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001855 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1856 apps = mBackupParticipants.get(Binder.getCallingUid());
1857 } else {
1858 // a caller with full permission can ask to back up any participating app
1859 // !!! TODO: allow data-clear of ANY app?
1860 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1861 apps = new HashSet<ApplicationInfo>();
1862 int N = mBackupParticipants.size();
1863 for (int i = 0; i < N; i++) {
1864 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1865 if (s != null) {
1866 apps.addAll(s);
1867 }
1868 }
1869 }
1870
1871 // now find the given package in the set of candidate apps
1872 for (ApplicationInfo app : apps) {
1873 if (app.packageName.equals(packageName)) {
1874 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1875 // found it; fire off the clear request
1876 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001877 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001878 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001879 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1880 new ClearParams(getTransport(mCurrentTransport), info));
1881 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001882 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001883 }
1884 break;
1885 }
1886 }
1887 }
1888
Christopher Tateace7f092009-06-15 18:07:25 -07001889 // Run a backup pass immediately for any applications that have declared
1890 // that they have pending updates.
1891 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001893
Christopher Tateace7f092009-06-15 18:07:25 -07001894 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001895 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001896 // Because the alarms we are using can jitter, and we want an *immediate*
1897 // backup pass to happen, we restart the timer beginning with "next time,"
1898 // then manually fire the backup trigger intent ourselves.
1899 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001900 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001901 mRunBackupIntent.send();
1902 } catch (PendingIntent.CanceledException e) {
1903 // should never happen
1904 Log.e(TAG, "run-backup intent cancelled!");
1905 }
Christopher Tate46758122009-05-06 11:22:00 -07001906 }
1907 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001908
Christopher Tate8031a3d2009-07-06 16:36:05 -07001909 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001910 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001911 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1912 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001913
Christopher Tate4cc86e12009-09-21 19:36:51 -07001914 Log.i(TAG, "Backup enabled => " + enable);
1915
Christopher Tate6ef58a12009-06-29 14:56:28 -07001916 boolean wasEnabled = mEnabled;
1917 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001918 Settings.Secure.putInt(mContext.getContentResolver(),
1919 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001920 mEnabled = enable;
1921 }
1922
Christopher Tate49401dd2009-07-01 12:34:29 -07001923 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001924 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001925 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001926 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001927 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001928 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001929 if (DEBUG) Log.i(TAG, "Opting out of backup");
1930
Christopher Tateb6787f22009-07-02 17:40:45 -07001931 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001932
1933 // This also constitutes an opt-out, so we wipe any data for
1934 // this device from the backend. We start that process with
1935 // an alarm in order to guarantee wakelock states.
1936 if (wasEnabled && mProvisioned) {
1937 // NOTE: we currently flush every registered transport, not just
1938 // the currently-active one.
1939 HashSet<String> allTransports;
1940 synchronized (mTransports) {
1941 allTransports = new HashSet<String>(mTransports.keySet());
1942 }
1943 // build the set of transports for which we are posting an init
1944 for (String transport : allTransports) {
1945 recordInitPendingLocked(true, transport);
1946 }
1947 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1948 mRunInitIntent);
1949 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001950 }
1951 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001952 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001953
Christopher Tate8031a3d2009-07-06 16:36:05 -07001954 // Mark the backup service as having been provisioned
1955 public void setBackupProvisioned(boolean available) {
1956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1957 "setBackupProvisioned");
1958
1959 boolean wasProvisioned = mProvisioned;
1960 synchronized (this) {
1961 Settings.Secure.putInt(mContext.getContentResolver(),
1962 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1963 mProvisioned = available;
1964 }
1965
1966 synchronized (mQueueLock) {
1967 if (available && !wasProvisioned && mEnabled) {
1968 // we're now good to go, so start the backup alarms
1969 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1970 } else if (!available) {
1971 // No longer enabled, so stop running backups
1972 Log.w(TAG, "Backup service no longer provisioned");
1973 mAlarmManager.cancel(mRunBackupIntent);
1974 }
1975 }
1976 }
1977
1978 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1979 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1980 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1981 BACKUP_INTERVAL, mRunBackupIntent);
1982 }
1983
Christopher Tate6ef58a12009-06-29 14:56:28 -07001984 // Report whether the backup mechanism is currently enabled
1985 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001986 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001987 return mEnabled; // no need to synchronize just to read it
1988 }
1989
Christopher Tate91717492009-06-26 21:07:13 -07001990 // Report the name of the currently active transport
1991 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001993 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001994 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001995 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001996 }
1997
Christopher Tate91717492009-06-26 21:07:13 -07001998 // Report all known, available backup transports
1999 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002001
Christopher Tate91717492009-06-26 21:07:13 -07002002 String[] list = null;
2003 ArrayList<String> known = new ArrayList<String>();
2004 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2005 if (entry.getValue() != null) {
2006 known.add(entry.getKey());
2007 }
2008 }
2009
2010 if (known.size() > 0) {
2011 list = new String[known.size()];
2012 known.toArray(list);
2013 }
2014 return list;
2015 }
2016
2017 // Select which transport to use for the next backup operation. If the given
2018 // name is not one of the available transports, no action is taken and the method
2019 // returns null.
2020 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002021 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002022
2023 synchronized (mTransports) {
2024 String prevTransport = null;
2025 if (mTransports.get(transport) != null) {
2026 prevTransport = mCurrentTransport;
2027 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002028 Settings.Secure.putString(mContext.getContentResolver(),
2029 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002030 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2031 + " returning " + prevTransport);
2032 } else {
2033 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2034 }
2035 return prevTransport;
2036 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002037 }
2038
2039 // Callback: a requested backup agent has been instantiated. This should only
2040 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002041 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002042 synchronized(mAgentConnectLock) {
2043 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2044 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2045 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2046 mConnectedAgent = agent;
2047 mConnecting = false;
2048 } else {
2049 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2050 + " claiming agent connected");
2051 }
2052 mAgentConnectLock.notifyAll();
2053 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002054 }
2055
2056 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2057 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002058 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002059 public void agentDisconnected(String packageName) {
2060 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002061 synchronized(mAgentConnectLock) {
2062 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2063 mConnectedAgent = null;
2064 mConnecting = false;
2065 } else {
2066 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2067 + " claiming agent disconnected");
2068 }
2069 mAgentConnectLock.notifyAll();
2070 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002071 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002072
Christopher Tate8c850b72009-06-07 19:33:20 -07002073 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002074 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002076
2077 synchronized(this) {
2078 if (mActiveRestoreSession != null) {
2079 Log.d(TAG, "Restore session requested but one already active");
2080 return null;
2081 }
Christopher Tate91717492009-06-26 21:07:13 -07002082 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002083 }
2084 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002085 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002086
Christopher Tate9b3905c2009-06-08 15:24:01 -07002087 // ----- Restore session -----
2088
2089 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002090 private static final String TAG = "RestoreSession";
2091
Christopher Tate9b3905c2009-06-08 15:24:01 -07002092 private IBackupTransport mRestoreTransport = null;
2093 RestoreSet[] mRestoreSets = null;
2094
Christopher Tate91717492009-06-26 21:07:13 -07002095 RestoreSession(String transport) {
2096 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002097 }
2098
2099 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002100 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002101 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002102 "getAvailableRestoreSets");
2103
Christopher Tatef68eb502009-06-16 11:02:01 -07002104 try {
Christopher Tate43383042009-07-13 15:17:13 -07002105 if (mRestoreTransport == null) {
2106 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002107 return null;
2108 }
2109 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002110 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002112 }
2113 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002114 } catch (Exception e) {
2115 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2116 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002117 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002118 }
2119
Dan Egnor0084da52009-07-29 12:57:16 -07002120 public synchronized int performRestore(long token, IRestoreObserver observer) {
2121 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2122 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002123
Christopher Tatef2c321a2009-08-10 15:43:36 -07002124 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2125 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002126
Dan Egnor0084da52009-07-29 12:57:16 -07002127 if (mRestoreTransport == null || mRestoreSets == null) {
2128 Log.e(TAG, "Ignoring performRestore() with no restore set");
2129 return -1;
2130 }
2131
Christopher Tate21ab6a52009-09-24 18:01:46 -07002132 synchronized (mQueueLock) {
2133 if (mBackupOrRestoreInProgress) {
2134 Log.e(TAG, "Backup pass in progress, restore aborted");
2135 return -1;
2136 }
2137
2138 for (int i = 0; i < mRestoreSets.length; i++) {
2139 if (token == mRestoreSets[i].token) {
2140 long oldId = Binder.clearCallingIdentity();
2141 // Suppress backups until the restore operation is finished
2142 mBackupOrRestoreInProgress = true;
2143 mWakelock.acquire();
2144 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2145 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2146 mBackupHandler.sendMessage(msg);
2147 Binder.restoreCallingIdentity(oldId);
2148 return 0;
2149 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002150 }
2151 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002152
2153 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002154 return -1;
2155 }
2156
Dan Egnor0084da52009-07-29 12:57:16 -07002157 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002158 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002159 "endRestoreSession");
2160
Dan Egnor0084da52009-07-29 12:57:16 -07002161 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002162
Dan Egnor0084da52009-07-29 12:57:16 -07002163 synchronized (this) {
2164 try {
2165 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2166 } catch (Exception e) {
2167 Log.e(TAG, "Error in finishRestore", e);
2168 } finally {
2169 mRestoreTransport = null;
2170 }
2171 }
2172
2173 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002174 if (BackupManagerService.this.mActiveRestoreSession == this) {
2175 BackupManagerService.this.mActiveRestoreSession = null;
2176 } else {
2177 Log.e(TAG, "ending non-current restore session");
2178 }
2179 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002180 }
2181 }
2182
Christopher Tate043dadc2009-06-02 16:11:00 -07002183
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002184 @Override
2185 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2186 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002187 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
2188 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07002189 pw.println("Available transports:");
2190 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002191 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
2192 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07002193 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002194 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07002195 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002196 for (int i=0; i<N; i++) {
2197 int uid = mBackupParticipants.keyAt(i);
2198 pw.print(" uid: ");
2199 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002200 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2201 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002202 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002203 }
2204 }
Christopher Tate73e02522009-07-15 14:18:26 -07002205 pw.println("Ever backed up: " + mEverStoredApps.size());
2206 for (String pkg : mEverStoredApps) {
2207 pw.println(" " + pkg);
2208 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07002209 pw.println("Pending: " + mPendingBackups.size());
2210 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002211 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002212 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002213 }
2214 }
Christopher Tate487529a2009-04-29 14:03:25 -07002215}