blob: d4cebef7a0f3f7de5fbc1bae54a4e305be4309ae [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 Tate55f931a2009-09-29 17:17:34 -0700166 volatile long mLastBackupPass;
167 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700168
Christopher Tate55f931a2009-09-29 17:17:34 -0700169 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700170 final Object mClearDataLock = new Object();
171 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700172
Christopher Tate91717492009-06-26 21:07:13 -0700173 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700174 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700175 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700176 String mCurrentTransport;
177 IBackupTransport mLocalTransport, mGoogleTransport;
178 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700179
Christopher Tate73e02522009-07-15 14:18:26 -0700180 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181 public IBackupTransport transport;
182 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700183 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700184
Dan Egnor156411d2009-06-26 13:20:02 -0700185 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700186 transport = _transport;
187 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700188 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700189 }
190 }
191
Christopher Tate73e02522009-07-15 14:18:26 -0700192 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700193 public IBackupTransport transport;
194 public PackageInfo packageInfo;
195
196 ClearParams(IBackupTransport _transport, PackageInfo _info) {
197 transport = _transport;
198 packageInfo = _info;
199 }
200 }
201
Christopher Tate5cb400b2009-06-25 16:03:14 -0700202 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700203 File mBaseStateDir;
204 File mDataDir;
205 File mJournalDir;
206 File mJournal;
207 RandomAccessFile mJournalStream;
208
209 // Keep a log of all the apps we've ever backed up
210 private File mEverStored;
211 private RandomAccessFile mEverStoredStream;
212 HashSet<String> mEverStoredApps = new HashSet<String>();
213
Christopher Tate4cc86e12009-09-21 19:36:51 -0700214 // Persistently track the need to do a full init
215 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
216 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700217 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700218
Christopher Tate487529a2009-04-29 14:03:25 -0700219 public BackupManagerService(Context context) {
220 mContext = context;
221 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700222 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700223
Christopher Tateb6787f22009-07-02 17:40:45 -0700224 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
225 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
226
Christopher Tate22b87872009-05-04 16:41:53 -0700227 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700228 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700229 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700230 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700231 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700232 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700233 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700234
Christopher Tate4cc86e12009-09-21 19:36:51 -0700235 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700236 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700237 IntentFilter filter = new IntentFilter();
238 filter.addAction(RUN_BACKUP_ACTION);
239 context.registerReceiver(mRunBackupReceiver, filter,
240 android.Manifest.permission.BACKUP, null);
241
242 mRunInitReceiver = new RunInitializeReceiver();
243 filter = new IntentFilter();
244 filter.addAction(RUN_INITIALIZE_ACTION);
245 context.registerReceiver(mRunInitReceiver, filter,
246 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700247
248 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700249 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
250 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
251
Christopher Tate4cc86e12009-09-21 19:36:51 -0700252 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
253 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
254 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
255
Christopher Tatecde87f42009-06-12 12:55:53 -0700256 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700257 mJournalDir = new File(mBaseStateDir, "pending");
258 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700259 makeJournalLocked(); // okay because no other threads are running yet
260
Christopher Tate73e02522009-07-15 14:18:26 -0700261 // Set up the various sorts of package tracking we do
262 initPackageTracking();
263
Christopher Tateabce4e82009-06-18 18:35:32 -0700264 // Build our mapping of uid to backup client services. This implicitly
265 // schedules a backup pass on the Package Manager metadata the first
266 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700267 synchronized (mBackupParticipants) {
268 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700269 }
270
Dan Egnor87a02bc2009-06-17 02:30:10 -0700271 // Set up our transport options and initialize the default transport
272 // TODO: Have transports register themselves somehow?
273 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700274 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700275 ComponentName localName = new ComponentName(context, LocalTransport.class);
276 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700277
Christopher Tate91717492009-06-26 21:07:13 -0700278 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700279 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
280 Settings.Secure.BACKUP_TRANSPORT);
281 if ("".equals(mCurrentTransport)) {
282 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700283 }
Christopher Tate91717492009-06-26 21:07:13 -0700284 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
285
286 // Attach to the Google backup transport. When this comes up, it will set
287 // itself as the current transport because we explicitly reset mCurrentTransport
288 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700289 Intent intent = new Intent().setComponent(new ComponentName(
290 "com.google.android.backup",
291 "com.google.android.backup.BackupTransportService"));
292 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700293
Christopher Tatecde87f42009-06-12 12:55:53 -0700294 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700295 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700296 parseLeftoverJournals();
297
Christopher Tateb6787f22009-07-02 17:40:45 -0700298 // Power management
299 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
300
301 // Start the backup passes going
302 setBackupEnabled(areEnabled);
303 }
304
305 private class RunBackupReceiver extends BroadcastReceiver {
306 public void onReceive(Context context, Intent intent) {
307 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700308 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700309 if (mPendingInits.size() > 0) {
310 // If there are pending init operations, we process those
311 // and then settle into the usual periodic backup schedule.
312 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
313 try {
314 mAlarmManager.cancel(mRunInitIntent);
315 mRunInitIntent.send();
316 } catch (PendingIntent.CanceledException ce) {
317 Log.e(TAG, "Run init intent cancelled");
318 // can't really do more than bail here
319 }
320 } else {
321 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700322 // fully set up, in the middle of a backup already,
323 // or racing with an initialize pass.
324 if (mEnabled && mProvisioned
325 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700326 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700327 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700328
329 // Acquire the wakelock and pass it to the backup thread. it will
330 // be released once backup concludes.
331 mWakelock.acquire();
332
333 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
334 mBackupHandler.sendMessage(msg);
335 } else {
336 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700337 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700338 }
339 }
340 }
341 }
342 }
343 }
344
345 private class RunInitializeReceiver extends BroadcastReceiver {
346 public void onReceive(Context context, Intent intent) {
347 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
348 synchronized (mQueueLock) {
349 if (DEBUG) Log.v(TAG, "Running a device init");
350 mInitInProgress = true;
351
352 // Acquire the wakelock and pass it to the init thread. it will
353 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700354 mWakelock.acquire();
355
Christopher Tate4cc86e12009-09-21 19:36:51 -0700356 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700357 mBackupHandler.sendMessage(msg);
358 }
359 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700360 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700361 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700362
Christopher Tate73e02522009-07-15 14:18:26 -0700363 private void initPackageTracking() {
364 if (DEBUG) Log.v(TAG, "Initializing package tracking");
365
Christopher Tatee97e8072009-07-15 16:45:50 -0700366 // Keep a log of what apps we've ever backed up. Because we might have
367 // rebooted in the middle of an operation that was removing something from
368 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700369 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700370 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700371 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700372 // If there are previous contents, parse them out then start a new
373 // file to continue the recordkeeping.
374 if (mEverStored.exists()) {
375 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
376 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700377
Christopher Tatedfec20b2009-08-03 15:38:09 -0700378 // parse its existing contents
379 mEverStoredStream.seek(0);
380 temp.seek(0);
381 try {
382 while (true) {
383 PackageInfo info;
384 String pkg = mEverStoredStream.readUTF();
385 try {
386 info = mPackageManager.getPackageInfo(pkg, 0);
387 mEverStoredApps.add(pkg);
388 temp.writeUTF(pkg);
389 if (DEBUG) Log.v(TAG, " + " + pkg);
390 } catch (NameNotFoundException e) {
391 // nope, this package was uninstalled; don't include it
392 if (DEBUG) Log.v(TAG, " - " + pkg);
393 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700394 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700395 } catch (EOFException e) {
396 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700397 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700398
Christopher Tatedfec20b2009-08-03 15:38:09 -0700399 // Once we've rewritten the backup history log, atomically replace the
400 // old one with the new one then reopen the file for continuing use.
401 temp.close();
402 mEverStoredStream.close();
403 tempProcessedFile.renameTo(mEverStored);
404 }
405 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700406 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700407 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700408 } catch (IOException e) {
409 Log.e(TAG, "Unable to open known-stored file!");
410 mEverStoredStream = null;
411 }
412
Christopher Tatee97e8072009-07-15 16:45:50 -0700413 // If we were in the middle of removing something from the ever-backed-up
414 // file, there might be a transient "processed.new" file still present.
415 // We've reconstructed a coherent state at this point though, so we can
416 // safely discard that file now.
417 if (tempProcessedFile.exists()) {
418 tempProcessedFile.delete();
419 }
420
Christopher Tate73e02522009-07-15 14:18:26 -0700421 // Register for broadcasts about package install, etc., so we can
422 // update the provider list.
423 IntentFilter filter = new IntentFilter();
424 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
425 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
426 filter.addDataScheme("package");
427 mContext.registerReceiver(mBroadcastReceiver, filter);
428 }
429
Christopher Tatecde87f42009-06-12 12:55:53 -0700430 private void makeJournalLocked() {
431 try {
432 mJournal = File.createTempFile("journal", null, mJournalDir);
433 mJournalStream = new RandomAccessFile(mJournal, "rwd");
434 } catch (IOException e) {
435 Log.e(TAG, "Unable to write backup journals");
436 mJournal = null;
437 mJournalStream = null;
438 }
439 }
440
441 private void parseLeftoverJournals() {
442 if (mJournal != null) {
443 File[] allJournals = mJournalDir.listFiles();
444 for (File f : allJournals) {
445 if (f.compareTo(mJournal) != 0) {
446 // This isn't the current journal, so it must be a leftover. Read
447 // out the package names mentioned there and schedule them for
448 // backup.
449 try {
450 Log.i(TAG, "Found stale backup journal, scheduling:");
451 RandomAccessFile in = new RandomAccessFile(f, "r");
452 while (true) {
453 String packageName = in.readUTF();
454 Log.i(TAG, " + " + packageName);
455 dataChanged(packageName);
456 }
457 } catch (EOFException e) {
458 // no more data; we're done
459 } catch (Exception e) {
460 // can't read it or other error; just skip it
461 } finally {
462 // close/delete the file
463 f.delete();
464 }
465 }
466 }
467 }
468 }
469
Christopher Tate4cc86e12009-09-21 19:36:51 -0700470 // Maintain persistent state around whether need to do an initialize operation.
471 // Must be called with the queue lock held.
472 void recordInitPendingLocked(boolean isPending, String transportName) {
473 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
474 + " on transport " + transportName);
475 try {
476 IBackupTransport transport = getTransport(transportName);
477 String transportDirName = transport.transportDirName();
478 File stateDir = new File(mBaseStateDir, transportDirName);
479 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
480
481 if (isPending) {
482 // We need an init before we can proceed with sending backup data.
483 // Record that with an entry in our set of pending inits, as well as
484 // journaling it via creation of a sentinel file.
485 mPendingInits.add(transportName);
486 try {
487 (new FileOutputStream(initPendingFile)).close();
488 } catch (IOException ioe) {
489 // Something is badly wrong with our permissions; just try to move on
490 }
491 } else {
492 // No more initialization needed; wipe the journal and reset our state.
493 initPendingFile.delete();
494 mPendingInits.remove(transportName);
495 }
496 } catch (RemoteException e) {
497 // can't happen; the transport is local
498 }
499 }
500
Christopher Tated55e18a2009-09-21 10:12:59 -0700501 // Reset all of our bookkeeping, in response to having been told that
502 // the backend data has been wiped [due to idle expiry, for example],
503 // so we must re-upload all saved settings.
504 void resetBackupState(File stateFileDir) {
505 synchronized (mQueueLock) {
506 // Wipe the "what we've ever backed up" tracking
507 try {
508 // close the ever-stored journal...
509 if (mEverStoredStream != null) {
510 mEverStoredStream.close();
511 }
512 // ... so we can delete it and start over
513 mEverStored.delete();
514 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
515 } catch (IOException e) {
516 Log.e(TAG, "Unable to open known-stored file!");
517 mEverStoredStream = null;
518 }
519 mEverStoredApps.clear();
520
521 // Remove all the state files
522 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700523 // ... but don't touch the needs-init sentinel
524 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
525 sf.delete();
526 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700527 }
528
529 // Enqueue a new backup of every participant
530 int N = mBackupParticipants.size();
531 for (int i=0; i<N; i++) {
532 int uid = mBackupParticipants.keyAt(i);
533 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
534 for (ApplicationInfo app: participants) {
535 try {
536 dataChanged(app.packageName);
537 } catch (RemoteException e) {
538 // can't happen; we're in the same process
539 }
540 }
541 }
542 }
543 }
544
Christopher Tate91717492009-06-26 21:07:13 -0700545 // Add a transport to our set of available backends
546 private void registerTransport(String name, IBackupTransport transport) {
547 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700548 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700549 mTransports.put(name, transport);
550 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700551
552 // If the init sentinel file exists, we need to be sure to perform the init
553 // as soon as practical. We also create the state directory at registration
554 // time to ensure it's present from the outset.
555 try {
556 String transportName = transport.transportDirName();
557 File stateDir = new File(mBaseStateDir, transportName);
558 stateDir.mkdirs();
559
560 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
561 if (initSentinel.exists()) {
562 synchronized (mQueueLock) {
563 mPendingInits.add(transportName);
564
565 // TODO: pick a better starting time than now + 1 minute
566 long delay = 1000 * 60; // one minute, in milliseconds
567 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
568 System.currentTimeMillis() + delay, mRunInitIntent);
569 }
570 }
571 } catch (RemoteException e) {
572 // can't happen, the transport is local
573 }
Christopher Tate91717492009-06-26 21:07:13 -0700574 }
575
Christopher Tate3799bc22009-05-06 16:13:56 -0700576 // ----- Track installation/removal of packages -----
577 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
578 public void onReceive(Context context, Intent intent) {
579 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
580
581 Uri uri = intent.getData();
582 if (uri == null) {
583 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700584 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700585 String pkgName = uri.getSchemeSpecificPart();
586 if (pkgName == null) {
587 return;
588 }
589
590 String action = intent.getAction();
591 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
592 synchronized (mBackupParticipants) {
593 Bundle extras = intent.getExtras();
594 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
595 // The package was just upgraded
596 updatePackageParticipantsLocked(pkgName);
597 } else {
598 // The package was just added
599 addPackageParticipantsLocked(pkgName);
600 }
601 }
602 }
603 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
604 Bundle extras = intent.getExtras();
605 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
606 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
607 } else {
608 synchronized (mBackupParticipants) {
609 removePackageParticipantsLocked(pkgName);
610 }
611 }
612 }
613 }
614 };
615
Dan Egnor87a02bc2009-06-17 02:30:10 -0700616 // ----- Track connection to GoogleBackupTransport service -----
617 ServiceConnection mGoogleConnection = new ServiceConnection() {
618 public void onServiceConnected(ComponentName name, IBinder service) {
619 if (DEBUG) Log.v(TAG, "Connected to Google transport");
620 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700621 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700622 }
623
624 public void onServiceDisconnected(ComponentName name) {
625 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
626 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700627 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700628 }
629 };
630
Joe Onorato8ad02812009-05-13 01:41:44 -0400631 // ----- Run the actual backup process asynchronously -----
632
Christopher Tate181fafa2009-05-14 11:12:14 -0700633 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400634 public void handleMessage(Message msg) {
635
636 switch (msg.what) {
637 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700638 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700639 mLastBackupPass = System.currentTimeMillis();
640 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
641
Christopher Tate91717492009-06-26 21:07:13 -0700642 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700643 if (transport == null) {
644 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700645 synchronized (mQueueLock) {
646 mBackupOrRestoreInProgress = false;
647 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700648 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700649 break;
650 }
651
Joe Onorato8ad02812009-05-13 01:41:44 -0400652 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700653 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700654 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400655 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700656 // Do we have any work to do?
657 if (mPendingBackups.size() > 0) {
658 for (BackupRequest b: mPendingBackups.values()) {
659 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700660 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700661 Log.v(TAG, "clearing pending backups");
662 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700663
Christopher Tate49401dd2009-07-01 12:34:29 -0700664 // Start a new backup-queue journal file too
665 if (mJournalStream != null) {
666 try {
667 mJournalStream.close();
668 } catch (IOException e) {
669 // don't need to do anything
670 }
671 makeJournalLocked();
672 }
673
674 // At this point, we have started a new journal file, and the old
675 // file identity is being passed to the backup processing thread.
676 // When it completes successfully, that old journal file will be
677 // deleted. If we crash prior to that, the old journal is parsed
678 // at next boot and the journaled requests fulfilled.
679 (new PerformBackupThread(transport, queue, oldJournal)).start();
680 } else {
681 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700682 synchronized (mQueueLock) {
683 mBackupOrRestoreInProgress = false;
684 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700685 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700686 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400687 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700688 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700689 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700690
691 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400692 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700693
694 case MSG_RUN_RESTORE:
695 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700696 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400697 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700698 (new PerformRestoreThread(params.transport, params.observer,
699 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700700 break;
701 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700702
703 case MSG_RUN_CLEAR:
704 {
705 ClearParams params = (ClearParams)msg.obj;
706 (new PerformClearThread(params.transport, params.packageInfo)).start();
707 break;
708 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700709
710 case MSG_RUN_INITIALIZE:
711 {
712 HashSet<String> queue;
713
714 // Snapshot the pending-init queue and work on that
715 synchronized (mQueueLock) {
716 queue = new HashSet<String>(mPendingInits);
717 mPendingInits.clear();
718 }
719
720 (new PerformInitializeThread(queue)).start();
721 break;
722 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400723 }
724 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400725 }
726
Christopher Tate181fafa2009-05-14 11:12:14 -0700727 // Add the backup agents in the given package to our set of known backup participants.
728 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700729 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700730 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700731 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700732 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700733 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700734 }
735
Christopher Tate181fafa2009-05-14 11:12:14 -0700736 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700737 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700738 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700739 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
740 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700741 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700742 + " uid=" + p.applicationInfo.uid
743 + " killAfterRestore="
744 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
745 + " restoreNeedsApplication="
746 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
747 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700748 }
749 }
750
Dan Egnorefe52642009-06-24 00:16:33 -0700751 for (PackageInfo pkg : targetPkgs) {
752 if (packageName == null || pkg.packageName.equals(packageName)) {
753 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700754 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700755 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700756 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700757 mBackupParticipants.put(uid, set);
758 }
Dan Egnorefe52642009-06-24 00:16:33 -0700759 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700760
761 // If we've never seen this app before, schedule a backup for it
762 if (!mEverStoredApps.contains(pkg.packageName)) {
763 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
764 + " never backed up; scheduling");
765 try {
766 dataChanged(pkg.packageName);
767 } catch (RemoteException e) {
768 // can't happen; it's a local method call
769 }
770 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700771 }
Christopher Tate487529a2009-04-29 14:03:25 -0700772 }
773 }
774
Christopher Tate6785dd82009-06-18 15:58:25 -0700775 // Remove the given package's entry from our known active set. If
776 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700777 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700778 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700779 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700780 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700781 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700782 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700783 int flags = PackageManager.GET_SIGNATURES;
784 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700785 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700786 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700787 }
788 } else {
789 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700790 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700791 }
792 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700793 }
794
Joe Onorato8ad02812009-05-13 01:41:44 -0400795 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700796 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700797 if (DEBUG) {
798 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
799 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700800 for (PackageInfo p : agents) {
801 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700802 }
803 }
Dan Egnorefe52642009-06-24 00:16:33 -0700804 for (PackageInfo pkg : agents) {
805 if (packageName == null || pkg.packageName.equals(packageName)) {
806 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700807 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700808 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700809 // Find the existing entry with the same package name, and remove it.
810 // We can't just remove(app) because the instances are different.
811 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700812 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700813 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700814 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700815 break;
816 }
817 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700818 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700819 mBackupParticipants.delete(uid);
820 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700821 }
822 }
823 }
824 }
825
Christopher Tate181fafa2009-05-14 11:12:14 -0700826 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700827 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700828 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700829 int flags = PackageManager.GET_SIGNATURES;
830 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
831 int N = packages.size();
832 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700833 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700834 try {
835 ApplicationInfo app = pkg.applicationInfo;
836 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
837 || app.backupAgentName == null
838 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
839 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
840 packages.remove(a);
841 }
842 else {
843 // we will need the shared library path, so look that up and store it here
844 app = mPackageManager.getApplicationInfo(pkg.packageName,
845 PackageManager.GET_SHARED_LIBRARY_FILES);
846 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
847 }
848 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700849 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700850 }
851 }
Dan Egnorefe52642009-06-24 00:16:33 -0700852 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 }
Christopher Tateaa088442009-06-16 18:25:46 -0700854
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 // Reset the given package's known backup participants. Unlike add/remove, the update
856 // action cannot be passed a null package name.
857 void updatePackageParticipantsLocked(String packageName) {
858 if (packageName == null) {
859 Log.e(TAG, "updatePackageParticipants called with null package name");
860 return;
861 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700862 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700863
864 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700865 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700866 removePackageParticipantsLockedInner(packageName, allApps);
867 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700868 }
869
Christopher Tate73e02522009-07-15 14:18:26 -0700870 // Called from the backup thread: record that the given app has been successfully
871 // backed up at least once
872 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700873 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700874 synchronized (mEverStoredApps) {
875 if (mEverStoredApps.add(packageName)) {
876 try {
877 mEverStoredStream.writeUTF(packageName);
878 } catch (IOException e) {
879 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
880 try {
881 mEverStoredStream.close();
882 } catch (IOException ioe) {
883 // we're dropping it; no need to handle an exception on close here
884 }
885 mEverStoredStream = null;
886 }
887 }
888 }
889 }
890 }
891
Christopher Tatee97e8072009-07-15 16:45:50 -0700892 // Remove our awareness of having ever backed up the given package
893 void removeEverBackedUp(String packageName) {
894 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
895 + ", new set:");
896
897 if (mEverStoredStream != null) {
898 synchronized (mEverStoredApps) {
899 // Rewrite the file and rename to overwrite. If we reboot in the middle,
900 // we'll recognize on initialization time that the package no longer
901 // exists and fix it up then.
902 File tempKnownFile = new File(mBaseStateDir, "processed.new");
903 try {
904 mEverStoredStream.close();
905 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
906 mEverStoredApps.remove(packageName);
907 for (String s : mEverStoredApps) {
908 known.writeUTF(s);
909 if (DEBUG) Log.v(TAG, " " + s);
910 }
911 known.close();
912 tempKnownFile.renameTo(mEverStored);
913 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
914 } catch (IOException e) {
915 // Bad: we couldn't create the new copy. For safety's sake we
916 // abandon the whole process and remove all what's-backed-up
917 // state entirely, meaning we'll force a backup pass for every
918 // participant on the next boot or [re]install.
919 Log.w(TAG, "Error rewriting backed-up set; halting log");
920 mEverStoredStream = null;
921 mEverStoredApps.clear();
922 tempKnownFile.delete();
923 mEverStored.delete();
924 }
925 }
926 }
927 }
928
Dan Egnor87a02bc2009-06-17 02:30:10 -0700929 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700930 private IBackupTransport getTransport(String transportName) {
931 synchronized (mTransports) {
932 IBackupTransport transport = mTransports.get(transportName);
933 if (transport == null) {
934 Log.w(TAG, "Requested unavailable transport: " + transportName);
935 }
936 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700937 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700938 }
939
Christopher Tatedf01dea2009-06-09 20:45:02 -0700940 // fire off a backup agent, blocking until it attaches or times out
941 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
942 IBackupAgent agent = null;
943 synchronized(mAgentConnectLock) {
944 mConnecting = true;
945 mConnectedAgent = null;
946 try {
947 if (mActivityManager.bindBackupAgent(app, mode)) {
948 Log.d(TAG, "awaiting agent for " + app);
949
950 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700951 // only wait 10 seconds for the clear data to happen
952 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
953 while (mConnecting && mConnectedAgent == null
954 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700955 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700956 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700957 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700958 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700959 return null;
960 }
961 }
962
963 // if we timed out with no connect, abort and move on
964 if (mConnecting == true) {
965 Log.w(TAG, "Timeout waiting for agent " + app);
966 return null;
967 }
968 agent = mConnectedAgent;
969 }
970 } catch (RemoteException e) {
971 // can't happen
972 }
973 }
974 return agent;
975 }
976
Christopher Tatec7b31e32009-06-10 15:49:30 -0700977 // clear an application's data, blocking until the operation completes or times out
978 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700979 // Don't wipe packages marked allowClearUserData=false
980 try {
981 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
982 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
983 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
984 + packageName);
985 return;
986 }
987 } catch (NameNotFoundException e) {
988 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
989 return;
990 }
991
Christopher Tatec7b31e32009-06-10 15:49:30 -0700992 ClearDataObserver observer = new ClearDataObserver();
993
994 synchronized(mClearDataLock) {
995 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700996 /* This is causing some critical processes to be killed during setup.
997 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700998 try {
999 mActivityManager.clearApplicationUserData(packageName, observer);
1000 } catch (RemoteException e) {
1001 // can't happen because the activity manager is in this process
1002 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001003 */
1004 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001005
1006 // only wait 10 seconds for the clear data to happen
1007 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1008 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1009 try {
1010 mClearDataLock.wait(5000);
1011 } catch (InterruptedException e) {
1012 // won't happen, but still.
1013 mClearingData = false;
1014 }
1015 }
1016 }
1017 }
1018
1019 class ClearDataObserver extends IPackageDataObserver.Stub {
1020 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -07001021 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001022 synchronized(mClearDataLock) {
1023 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001024 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001025 }
1026 }
1027 }
1028
Christopher Tate043dadc2009-06-02 16:11:00 -07001029 // ----- Back up a set of applications via a worker thread -----
1030
1031 class PerformBackupThread extends Thread {
1032 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001033 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001034 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001035 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001036 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001037
Christopher Tateaa088442009-06-16 18:25:46 -07001038 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001039 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001040 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001041 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001042 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001043
1044 try {
1045 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1046 } catch (RemoteException e) {
1047 // can't happen; the transport is local
1048 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001049 }
1050
1051 @Override
1052 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001053 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001054 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001055 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1056
Christopher Tate79588342009-06-30 16:11:49 -07001057 // Backups run at background priority
1058 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1059
Christopher Tate043dadc2009-06-02 16:11:00 -07001060 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001061 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001062
1063 // If we haven't stored anything yet, we need to do an init operation.
1064 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
1065 status = mTransport.initializeDevice();
1066 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001067
1068 // The package manager doesn't have a proper <application> etc, but since
1069 // it's running here in the system process we can just set up its agent
1070 // directly and use a synthetic BackupRequest. We always run this pass
1071 // because it's cheap and this way we guarantee that we don't get out of
1072 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001073 if (status == BackupConstants.TRANSPORT_OK) {
1074 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1075 mPackageManager, allAgentPackages());
1076 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1077 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1078 status = processOneBackup(pmRequest,
1079 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1080 }
Christopher Tate90967f42009-09-20 15:28:33 -07001081
Dan Egnor01445162009-09-21 17:04:05 -07001082 if (status == BackupConstants.TRANSPORT_OK) {
1083 // Now run all the backups in our queue
1084 status = doQueuedBackups(mTransport);
1085 }
1086
1087 if (status == BackupConstants.TRANSPORT_OK) {
1088 // Tell the transport to finish everything it has buffered
1089 status = mTransport.finishBackup();
1090 if (status == BackupConstants.TRANSPORT_OK) {
1091 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1092 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1093 } else {
1094 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "");
1095 Log.e(TAG, "Transport error in finishBackup()");
1096 }
1097 }
1098
Dan Egnor01445162009-09-21 17:04:05 -07001099 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001100 // The backend reports that our dataset has been wiped. We need to
1101 // reset all of our bookkeeping and instead run a new backup pass for
1102 // everything.
1103 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1104 resetBackupState(mStateDir);
1105 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001106 }
1107 } catch (Exception e) {
1108 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001109 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001110 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001111 // If things went wrong, we need to re-stage the apps we had expected
1112 // to be backing up in this pass. This journals the package names in
1113 // the current active pending-backup file, not in the we are holding
1114 // here in mJournal.
1115 if (status != BackupConstants.TRANSPORT_OK) {
1116 Log.w(TAG, "Backup pass unsuccessful, restaging");
1117 for (BackupRequest req : mQueue) {
1118 try {
1119 dataChanged(req.appInfo.packageName);
1120 } catch (RemoteException e) {
1121 // can't happen; it's a local call
1122 }
1123 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001124
1125 // We also want to reset the backup schedule based on whatever
1126 // the transport suggests by way of retry/backoff time.
1127 try {
1128 startBackupAlarmsLocked(mTransport.requestBackupTime());
1129 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001130 }
1131
1132 // Either backup was successful, in which case we of course do not need
1133 // this pass's journal any more; or it failed, in which case we just
1134 // re-enqueued all of these packages in the current active journal.
1135 // Either way, we no longer need this pass's journal.
1136 if (!mJournal.delete()) {
1137 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1138 }
1139
Christopher Tate21ab6a52009-09-24 18:01:46 -07001140 // Only once we're entirely finished do we indicate our completion
1141 // and release the wakelock
1142 synchronized (mQueueLock) {
1143 mBackupOrRestoreInProgress = false;
1144 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001145 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001146 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001147 }
1148
Dan Egnor01445162009-09-21 17:04:05 -07001149 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001150 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001151 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001152
Christopher Tate0749dcd2009-08-13 15:13:03 -07001153 // Don't run backup, even if requested, if the target app does not have
1154 // the requisite permission
1155 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1156 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1157 Log.w(TAG, "Skipping backup of unprivileged package "
1158 + request.appInfo.packageName);
1159 continue;
1160 }
1161
Christopher Tate043dadc2009-06-02 16:11:00 -07001162 IBackupAgent agent = null;
1163 int mode = (request.fullBackup)
1164 ? IApplicationThread.BACKUP_MODE_FULL
1165 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1166 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001167 agent = bindToAgentSynchronous(request.appInfo, mode);
1168 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001169 int result = processOneBackup(request, agent, transport);
1170 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001171 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001172 } catch (SecurityException ex) {
1173 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001174 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001175 } finally {
1176 try { // unbind even on timeout, just in case
1177 mActivityManager.unbindBackupAgent(request.appInfo);
1178 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001179 }
1180 }
Dan Egnor01445162009-09-21 17:04:05 -07001181
1182 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001183 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001184
Dan Egnor01445162009-09-21 17:04:05 -07001185 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1186 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001187 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001188 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001189
Dan Egnorbb9001c2009-07-27 12:20:13 -07001190 File savedStateName = new File(mStateDir, packageName);
1191 File backupDataName = new File(mDataDir, packageName + ".data");
1192 File newStateName = new File(mStateDir, packageName + ".new");
1193
1194 ParcelFileDescriptor savedState = null;
1195 ParcelFileDescriptor backupData = null;
1196 ParcelFileDescriptor newState = null;
1197
1198 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001199 try {
1200 // Look up the package info & signatures. This is first so that if it
1201 // throws an exception, there's no file setup yet that would need to
1202 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001203 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1204 // The metadata 'package' is synthetic
1205 packInfo = new PackageInfo();
1206 packInfo.packageName = packageName;
1207 } else {
1208 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001209 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001210 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001211
Christopher Tatec7b31e32009-06-10 15:49:30 -07001212 // In a full backup, we pass a null ParcelFileDescriptor as
1213 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001214 if (!request.fullBackup) {
1215 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001216 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001217 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1218 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001219
Dan Egnorbb9001c2009-07-27 12:20:13 -07001220 backupData = ParcelFileDescriptor.open(backupDataName,
1221 ParcelFileDescriptor.MODE_READ_WRITE |
1222 ParcelFileDescriptor.MODE_CREATE |
1223 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001224
Dan Egnorbb9001c2009-07-27 12:20:13 -07001225 newState = ParcelFileDescriptor.open(newStateName,
1226 ParcelFileDescriptor.MODE_READ_WRITE |
1227 ParcelFileDescriptor.MODE_CREATE |
1228 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001229
1230 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001231 agent.doBackup(savedState, backupData, newState);
1232 logBackupComplete(packageName);
1233 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001234 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001235 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001236 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1237 backupDataName.delete();
1238 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001239 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001240 } finally {
1241 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1242 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1243 try { if (newState != null) newState.close(); } catch (IOException e) {}
1244 savedState = backupData = newState = null;
1245 }
1246
1247 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001248 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001249 try {
1250 int size = (int) backupDataName.length();
1251 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001252 if (result == BackupConstants.TRANSPORT_OK) {
1253 backupData = ParcelFileDescriptor.open(backupDataName,
1254 ParcelFileDescriptor.MODE_READ_ONLY);
1255 result = transport.performBackup(packInfo, backupData);
1256 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001257
Dan Egnor83861e72009-09-17 16:17:55 -07001258 // TODO - We call finishBackup() for each application backed up, because
1259 // we need to know now whether it succeeded or failed. Instead, we should
1260 // hold off on finishBackup() until the end, which implies holding off on
1261 // renaming *all* the output state files (see below) until that happens.
1262
Dan Egnor01445162009-09-21 17:04:05 -07001263 if (result == BackupConstants.TRANSPORT_OK) {
1264 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001265 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001266 } else {
1267 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1268 }
1269
1270 // After successful transport, delete the now-stale data
1271 // and juggle the files so that next time we supply the agent
1272 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001273 if (result == BackupConstants.TRANSPORT_OK) {
1274 backupDataName.delete();
1275 newStateName.renameTo(savedStateName);
1276 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1277 } else {
1278 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1279 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001280 } catch (Exception e) {
1281 Log.e(TAG, "Transport error backing up " + packageName, e);
1282 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001283 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001284 } finally {
1285 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001286 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001287
Dan Egnor01445162009-09-21 17:04:05 -07001288 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001289 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001290 }
1291
Christopher Tatedf01dea2009-06-09 20:45:02 -07001292
1293 // ----- Restore handling -----
1294
Christopher Tateabce4e82009-06-18 18:35:32 -07001295 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001296 // Allow unsigned apps, but not signed on one device and unsigned on the other
1297 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001298 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1299 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001300 if ((storedSigs == null || storedSigs.length == 0)
1301 && (deviceSigs == null || deviceSigs.length == 0)) {
1302 return true;
1303 }
1304 if (storedSigs == null || deviceSigs == null) {
1305 return false;
1306 }
1307
Christopher Tateabce4e82009-06-18 18:35:32 -07001308 // !!! TODO: this demands that every stored signature match one
1309 // that is present on device, and does not demand the converse.
1310 // Is this this right policy?
1311 int nStored = storedSigs.length;
1312 int nDevice = deviceSigs.length;
1313
1314 for (int i=0; i < nStored; i++) {
1315 boolean match = false;
1316 for (int j=0; j < nDevice; j++) {
1317 if (storedSigs[i].equals(deviceSigs[j])) {
1318 match = true;
1319 break;
1320 }
1321 }
1322 if (!match) {
1323 return false;
1324 }
1325 }
1326 return true;
1327 }
1328
Christopher Tatedf01dea2009-06-09 20:45:02 -07001329 class PerformRestoreThread extends Thread {
1330 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001331 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001332 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001333 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001334
Christopher Tate5cbbf562009-06-22 16:44:51 -07001335 class RestoreRequest {
1336 public PackageInfo app;
1337 public int storedAppVersion;
1338
1339 RestoreRequest(PackageInfo _app, int _version) {
1340 app = _app;
1341 storedAppVersion = _version;
1342 }
1343 }
1344
Christopher Tate7d562ec2009-06-25 18:03:43 -07001345 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001346 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001347 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001348 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001349 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001350 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001351
1352 try {
1353 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1354 } catch (RemoteException e) {
1355 // can't happen; the transport is local
1356 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001357 }
1358
1359 @Override
1360 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001361 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001362 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001363 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001364 /**
1365 * Restore sequence:
1366 *
Dan Egnorefe52642009-06-24 00:16:33 -07001367 * 1. get the restore set description for our identity
1368 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001369 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001370 * 3. for each app in the restore queue:
1371 * 3.a. clear the app data
1372 * 3.b. get the restore data for the app from the transport
1373 * 3.c. launch the backup agent for the app
1374 * 3.d. agent.doRestore() with the data from the server
1375 * 3.e. unbind the agent [and kill the app?]
1376 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001377 *
1378 * On errors, we try our best to recover and move on to the next
1379 * application, but if necessary we abort the whole operation --
1380 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001381 */
1382
Christopher Tate7d562ec2009-06-25 18:03:43 -07001383 int error = -1; // assume error
1384
Dan Egnorefe52642009-06-24 00:16:33 -07001385 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001386 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001387 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001388 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001389
Dan Egnorefe52642009-06-24 00:16:33 -07001390 // Get the list of all packages which have backup enabled.
1391 // (Include the Package Manager metadata pseudo-package first.)
1392 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1393 PackageInfo omPackage = new PackageInfo();
1394 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1395 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001396
Dan Egnorefe52642009-06-24 00:16:33 -07001397 List<PackageInfo> agentPackages = allAgentPackages();
1398 restorePackages.addAll(agentPackages);
1399
Christopher Tate7d562ec2009-06-25 18:03:43 -07001400 // let the observer know that we're running
1401 if (mObserver != null) {
1402 try {
1403 // !!! TODO: get an actual count from the transport after
1404 // its startRestore() runs?
1405 mObserver.restoreStarting(restorePackages.size());
1406 } catch (RemoteException e) {
1407 Log.d(TAG, "Restore observer died at restoreStarting");
1408 mObserver = null;
1409 }
1410 }
1411
Dan Egnor01445162009-09-21 17:04:05 -07001412 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1413 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001414 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001415 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001416 return;
1417 }
1418
1419 String packageName = mTransport.nextRestorePackage();
1420 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001421 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001422 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001423 return;
1424 } else if (packageName.equals("")) {
1425 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001426 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1427 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001428 return;
1429 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1430 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1431 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001432 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1433 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001434 return;
1435 }
1436
1437 // Pull the Package Manager metadata from the restore set first
1438 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1439 mPackageManager, agentPackages);
1440 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1441
Christopher Tate8c032472009-07-02 14:28:47 -07001442 // Verify that the backup set includes metadata. If not, we can't do
1443 // signature/version verification etc, so we simply do not proceed with
1444 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001445 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001446 Log.e(TAG, "No restore metadata available, so not restoring settings");
1447 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1448 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001449 return;
1450 }
1451
Christopher Tate7d562ec2009-06-25 18:03:43 -07001452 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001453 for (;;) {
1454 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001455
Dan Egnorefe52642009-06-24 00:16:33 -07001456 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001457 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001458 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001459 return;
1460 } else if (packageName.equals("")) {
1461 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001462 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001463
Christopher Tate7d562ec2009-06-25 18:03:43 -07001464 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001465 try {
1466 mObserver.onUpdate(count);
1467 } catch (RemoteException e) {
1468 Log.d(TAG, "Restore observer died in onUpdate");
1469 mObserver = null;
1470 }
1471 }
1472
Dan Egnorefe52642009-06-24 00:16:33 -07001473 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1474 if (metaInfo == null) {
1475 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001476 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1477 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001478 continue;
1479 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001480
Dan Egnorbb9001c2009-07-27 12:20:13 -07001481 PackageInfo packageInfo;
1482 try {
1483 int flags = PackageManager.GET_SIGNATURES;
1484 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1485 } catch (NameNotFoundException e) {
1486 Log.e(TAG, "Invalid package restoring data", e);
1487 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1488 "Package missing on device");
1489 continue;
1490 }
1491
Dan Egnorefe52642009-06-24 00:16:33 -07001492 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001493 String message = "Version " + metaInfo.versionCode
1494 + " > installed version " + packageInfo.versionCode;
1495 Log.w(TAG, "Package " + packageName + ": " + message);
1496 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001497 continue;
1498 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001499
Dan Egnorefe52642009-06-24 00:16:33 -07001500 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1501 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001502 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1503 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001504 continue;
1505 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001506
Dan Egnorefe52642009-06-24 00:16:33 -07001507 if (DEBUG) Log.v(TAG, "Package " + packageName
1508 + " restore version [" + metaInfo.versionCode
1509 + "] is compatible with installed version ["
1510 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001511
Christopher Tate5e1ab332009-09-01 20:32:49 -07001512 // Now perform the actual restore: first clear the app's data
1513 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001514 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001515
1516 // Then set up and bind the agent (with a restricted Application object
1517 // unless the application says otherwise)
1518 boolean useRealApp = (packageInfo.applicationInfo.flags
1519 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1520 if (DEBUG && useRealApp) {
1521 Log.v(TAG, "agent requires real Application subclass for restore");
1522 }
Dan Egnorefe52642009-06-24 00:16:33 -07001523 IBackupAgent agent = bindToAgentSynchronous(
1524 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001525 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1526 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001527 if (agent == null) {
1528 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001529 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1530 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001531 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001532 }
1533
Christopher Tate5e1ab332009-09-01 20:32:49 -07001534 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001535 try {
1536 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001537 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001538 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001539 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001540 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001541
1542 // The agent was probably running with a stub Application object,
1543 // which isn't a valid run mode for the main app logic. Shut
1544 // down the app so that next time it's launched, it gets the
1545 // usual full initialization.
1546 if ((packageInfo.applicationInfo.flags
1547 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1548 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1549 + packageInfo.applicationInfo.processName);
1550 mActivityManager.killApplicationProcess(
1551 packageInfo.applicationInfo.processName,
1552 packageInfo.applicationInfo.uid);
1553 }
Dan Egnorefe52642009-06-24 00:16:33 -07001554 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001555 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001556
1557 // if we get this far, report success to the observer
1558 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001559 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1560 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1561 } catch (Exception e) {
1562 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001563 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001564 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1565
Dan Egnorefe52642009-06-24 00:16:33 -07001566 try {
1567 mTransport.finishRestore();
1568 } catch (RemoteException e) {
1569 Log.e(TAG, "Error finishing restore", e);
1570 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001571
1572 if (mObserver != null) {
1573 try {
1574 mObserver.restoreFinished(error);
1575 } catch (RemoteException e) {
1576 Log.d(TAG, "Restore observer died at restoreFinished");
1577 }
1578 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001579
1580 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001581 synchronized (mQueueLock) {
1582 mBackupOrRestoreInProgress = false;
1583 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001584 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001585 }
1586 }
1587
Dan Egnorefe52642009-06-24 00:16:33 -07001588 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1589 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001590 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001591 final String packageName = app.packageName;
1592
Dan Egnorbb9001c2009-07-27 12:20:13 -07001593 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001594
Christopher Tate0749dcd2009-08-13 15:13:03 -07001595 // Don't restore to unprivileged packages
1596 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1597 packageName) != PackageManager.PERMISSION_GRANTED) {
1598 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1599 }
1600
Christopher Tatec7b31e32009-06-10 15:49:30 -07001601 // !!! TODO: get the dirs from the transport
1602 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001603 File newStateName = new File(mStateDir, packageName + ".new");
1604 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001605
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 ParcelFileDescriptor backupData = null;
1607 ParcelFileDescriptor newState = null;
1608
1609 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001610 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001611 backupData = ParcelFileDescriptor.open(backupDataName,
1612 ParcelFileDescriptor.MODE_READ_WRITE |
1613 ParcelFileDescriptor.MODE_CREATE |
1614 ParcelFileDescriptor.MODE_TRUNCATE);
1615
Dan Egnor01445162009-09-21 17:04:05 -07001616 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001617 Log.e(TAG, "Error getting restore data for " + packageName);
1618 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1619 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001620 }
1621
1622 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001624 backupData = ParcelFileDescriptor.open(backupDataName,
1625 ParcelFileDescriptor.MODE_READ_ONLY);
1626
Dan Egnorbb9001c2009-07-27 12:20:13 -07001627 newState = ParcelFileDescriptor.open(newStateName,
1628 ParcelFileDescriptor.MODE_READ_WRITE |
1629 ParcelFileDescriptor.MODE_CREATE |
1630 ParcelFileDescriptor.MODE_TRUNCATE);
1631
1632 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001633
1634 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001635 //
1636 // !!! TODO: the restored data should be migrated on the server
1637 // side into the current dataset. In that case the new state file
1638 // we just created would reflect the data already extant in the
1639 // backend, so there'd be nothing more to do. Until that happens,
1640 // however, we need to make sure that we record the data to the
1641 // current backend dataset. (Yes, this means shipping the data over
1642 // the wire in both directions. That's bad, but consistency comes
1643 // first, then efficiency.) Once we introduce server-side data
1644 // migration to the newly-restored device's dataset, we will change
1645 // the following from a discard of the newly-written state to the
1646 // "correct" operation of renaming into the canonical state blob.
1647 newStateName.delete(); // TODO: remove; see above comment
1648 //newStateName.renameTo(savedStateName); // TODO: replace with this
1649
Dan Egnorbb9001c2009-07-27 12:20:13 -07001650 int size = (int) backupDataName.length();
1651 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001652 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001653 Log.e(TAG, "Error restoring data for " + packageName, e);
1654 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1655
Christopher Tate96733042009-07-20 14:49:13 -07001656 // If the agent fails restore, it might have put the app's data
1657 // into an incoherent state. For consistency we wipe its data
1658 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001659 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001660 } finally {
1661 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001662 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1663 try { if (newState != null) newState.close(); } catch (IOException e) {}
1664 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001665 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001666 }
1667 }
1668
Christopher Tateee0e78a2009-07-02 11:17:03 -07001669 class PerformClearThread extends Thread {
1670 IBackupTransport mTransport;
1671 PackageInfo mPackage;
1672
1673 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1674 mTransport = transport;
1675 mPackage = packageInfo;
1676 }
1677
1678 @Override
1679 public void run() {
1680 try {
1681 // Clear the on-device backup state to ensure a full backup next time
1682 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1683 File stateFile = new File(stateDir, mPackage.packageName);
1684 stateFile.delete();
1685
1686 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001687 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001688 mTransport.clearBackupData(mPackage);
1689 } catch (RemoteException e) {
1690 // can't happen; the transport is local
1691 } finally {
1692 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001693 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001694 mTransport.finishBackup();
1695 } catch (RemoteException e) {
1696 // can't happen; the transport is local
1697 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001698
1699 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001700 synchronized (mQueueLock) {
1701 mBackupOrRestoreInProgress = false;
1702 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001703 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001704 }
1705 }
1706 }
1707
Christopher Tate4cc86e12009-09-21 19:36:51 -07001708 class PerformInitializeThread extends Thread {
1709 HashSet<String> mQueue;
1710
1711 PerformInitializeThread(HashSet<String> transportNames) {
1712 mQueue = transportNames;
1713 }
1714
1715 @Override
1716 public void run() {
1717 int status;
1718 try {
1719 for (String transportName : mQueue) {
1720 IBackupTransport transport = getTransport(transportName);
1721 if (transport == null) {
1722 Log.e(TAG, "Requested init for " + transportName + " but not found");
1723 continue;
1724 }
1725
1726 status = BackupConstants.TRANSPORT_OK;
1727 File stateDir = null;
1728
1729 Log.i(TAG, "Device init on " + transport.transportDirName());
1730
1731 stateDir = new File(mBaseStateDir, transport.transportDirName());
1732
1733 status = transport.initializeDevice();
1734 if (status != BackupConstants.TRANSPORT_OK) {
1735 Log.e(TAG, "Error from initializeDevice: " + status);
1736 }
1737 if (status == BackupConstants.TRANSPORT_OK) {
1738 status = transport.finishBackup();
1739 }
1740
1741 // Okay, the wipe really happened. Clean up our local bookkeeping.
1742 if (status == BackupConstants.TRANSPORT_OK) {
1743 resetBackupState(stateDir);
1744 synchronized (mQueueLock) {
1745 recordInitPendingLocked(false, transportName);
1746 }
1747 }
1748
1749 // If this didn't work, requeue this one and try again
1750 // after a suitable interval
1751 if (status != BackupConstants.TRANSPORT_OK) {
1752 Log.i(TAG, "Device init failed");
1753 synchronized (mQueueLock) {
1754 recordInitPendingLocked(true, transportName);
1755 }
1756 // do this via another alarm to make sure of the wakelock states
1757 long delay = transport.requestBackupTime();
1758 if (DEBUG) Log.w(TAG, "init failed on "
1759 + transportName + " resched in " + delay);
1760 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1761 System.currentTimeMillis() + delay, mRunInitIntent);
1762 } else {
1763 // success!
1764 Log.i(TAG, "Device init successful");
1765 }
1766
1767 }
1768 } catch (RemoteException e) {
1769 // can't happen; the transports are local
1770 } catch (Exception e) {
1771 Log.e(TAG, "Unexpected error performing init", e);
1772 } finally {
1773 // Done; indicate that we're finished and release the wakelock
1774 synchronized (mQueueLock) {
1775 mInitInProgress = false;
1776 }
1777 mWakelock.release();
1778 }
1779 }
1780 }
1781
Christopher Tatedf01dea2009-06-09 20:45:02 -07001782
Christopher Tate487529a2009-04-29 14:03:25 -07001783 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001784
Christopher Tatea8bf8152009-04-30 11:36:21 -07001785 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001786 // Record that we need a backup pass for the caller. Since multiple callers
1787 // may share a uid, we need to note all candidates within that uid and schedule
1788 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001789 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001790
Christopher Tate63d27002009-06-16 17:16:42 -07001791 // If the caller does not hold the BACKUP permission, it can only request a
1792 // backup of its own data.
1793 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001794 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001795 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1796 targets = mBackupParticipants.get(Binder.getCallingUid());
1797 } else {
1798 // a caller with full permission can ask to back up any participating app
1799 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001800 targets = new HashSet<ApplicationInfo>();
1801 int N = mBackupParticipants.size();
1802 for (int i = 0; i < N; i++) {
1803 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1804 if (s != null) {
1805 targets.addAll(s);
1806 }
1807 }
1808 }
Christopher Tate487529a2009-04-29 14:03:25 -07001809 if (targets != null) {
1810 synchronized (mQueueLock) {
1811 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001812 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001813 // validate the caller-supplied package name against the known set of
1814 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001815 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001816 // Add the caller to the set of pending backups. If there is
1817 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001818 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001819 if (mPendingBackups.put(app, req) == null) {
1820 // Journal this request in case of crash. The put()
1821 // operation returned null when this package was not already
1822 // in the set; we want to avoid touching the disk redundantly.
1823 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001824
Christopher Tate22b60d82009-07-07 16:36:02 -07001825 if (DEBUG) {
1826 int numKeys = mPendingBackups.size();
1827 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1828 for (BackupRequest b : mPendingBackups.values()) {
1829 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1830 }
1831 }
1832 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001833 }
1834 }
Christopher Tate487529a2009-04-29 14:03:25 -07001835 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001836 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001837 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1838 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001839 }
1840 }
Christopher Tate46758122009-05-06 11:22:00 -07001841
Christopher Tatecde87f42009-06-12 12:55:53 -07001842 private void writeToJournalLocked(String str) {
1843 if (mJournalStream != null) {
1844 try {
1845 mJournalStream.writeUTF(str);
1846 } catch (IOException e) {
1847 Log.e(TAG, "Error writing to backup journal");
1848 mJournalStream = null;
1849 mJournal = null;
1850 }
1851 }
1852 }
1853
Christopher Tateee0e78a2009-07-02 11:17:03 -07001854 // Clear the given package's backup data from the current transport
1855 public void clearBackupData(String packageName) {
1856 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1857 PackageInfo info;
1858 try {
1859 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1860 } catch (NameNotFoundException e) {
1861 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1862 return;
1863 }
1864
1865 // If the caller does not hold the BACKUP permission, it can only request a
1866 // wipe of its own backed-up data.
1867 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001868 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001869 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1870 apps = mBackupParticipants.get(Binder.getCallingUid());
1871 } else {
1872 // a caller with full permission can ask to back up any participating app
1873 // !!! TODO: allow data-clear of ANY app?
1874 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1875 apps = new HashSet<ApplicationInfo>();
1876 int N = mBackupParticipants.size();
1877 for (int i = 0; i < N; i++) {
1878 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1879 if (s != null) {
1880 apps.addAll(s);
1881 }
1882 }
1883 }
1884
1885 // now find the given package in the set of candidate apps
1886 for (ApplicationInfo app : apps) {
1887 if (app.packageName.equals(packageName)) {
1888 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1889 // found it; fire off the clear request
1890 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001891 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001892 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001893 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1894 new ClearParams(getTransport(mCurrentTransport), info));
1895 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001896 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001897 }
1898 break;
1899 }
1900 }
1901 }
1902
Christopher Tateace7f092009-06-15 18:07:25 -07001903 // Run a backup pass immediately for any applications that have declared
1904 // that they have pending updates.
1905 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001907
Christopher Tateace7f092009-06-15 18:07:25 -07001908 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001909 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001910 // Because the alarms we are using can jitter, and we want an *immediate*
1911 // backup pass to happen, we restart the timer beginning with "next time,"
1912 // then manually fire the backup trigger intent ourselves.
1913 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001914 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001915 mRunBackupIntent.send();
1916 } catch (PendingIntent.CanceledException e) {
1917 // should never happen
1918 Log.e(TAG, "run-backup intent cancelled!");
1919 }
Christopher Tate46758122009-05-06 11:22:00 -07001920 }
1921 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001922
Christopher Tate8031a3d2009-07-06 16:36:05 -07001923 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001924 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1926 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001927
Christopher Tate4cc86e12009-09-21 19:36:51 -07001928 Log.i(TAG, "Backup enabled => " + enable);
1929
Christopher Tate6ef58a12009-06-29 14:56:28 -07001930 boolean wasEnabled = mEnabled;
1931 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001932 Settings.Secure.putInt(mContext.getContentResolver(),
1933 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001934 mEnabled = enable;
1935 }
1936
Christopher Tate49401dd2009-07-01 12:34:29 -07001937 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001938 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001939 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001940 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001941 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001942 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001943 if (DEBUG) Log.i(TAG, "Opting out of backup");
1944
Christopher Tateb6787f22009-07-02 17:40:45 -07001945 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001946
1947 // This also constitutes an opt-out, so we wipe any data for
1948 // this device from the backend. We start that process with
1949 // an alarm in order to guarantee wakelock states.
1950 if (wasEnabled && mProvisioned) {
1951 // NOTE: we currently flush every registered transport, not just
1952 // the currently-active one.
1953 HashSet<String> allTransports;
1954 synchronized (mTransports) {
1955 allTransports = new HashSet<String>(mTransports.keySet());
1956 }
1957 // build the set of transports for which we are posting an init
1958 for (String transport : allTransports) {
1959 recordInitPendingLocked(true, transport);
1960 }
1961 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1962 mRunInitIntent);
1963 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001964 }
1965 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001966 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001967
Christopher Tate8031a3d2009-07-06 16:36:05 -07001968 // Mark the backup service as having been provisioned
1969 public void setBackupProvisioned(boolean available) {
1970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1971 "setBackupProvisioned");
1972
1973 boolean wasProvisioned = mProvisioned;
1974 synchronized (this) {
1975 Settings.Secure.putInt(mContext.getContentResolver(),
1976 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1977 mProvisioned = available;
1978 }
1979
1980 synchronized (mQueueLock) {
1981 if (available && !wasProvisioned && mEnabled) {
1982 // we're now good to go, so start the backup alarms
1983 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1984 } else if (!available) {
1985 // No longer enabled, so stop running backups
1986 Log.w(TAG, "Backup service no longer provisioned");
1987 mAlarmManager.cancel(mRunBackupIntent);
1988 }
1989 }
1990 }
1991
1992 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1993 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1994 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1995 BACKUP_INTERVAL, mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001996 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001997 }
1998
Christopher Tate6ef58a12009-06-29 14:56:28 -07001999 // Report whether the backup mechanism is currently enabled
2000 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002002 return mEnabled; // no need to synchronize just to read it
2003 }
2004
Christopher Tate91717492009-06-26 21:07:13 -07002005 // Report the name of the currently active transport
2006 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002007 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002008 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002009 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002010 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002011 }
2012
Christopher Tate91717492009-06-26 21:07:13 -07002013 // Report all known, available backup transports
2014 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002015 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002016
Christopher Tate91717492009-06-26 21:07:13 -07002017 String[] list = null;
2018 ArrayList<String> known = new ArrayList<String>();
2019 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2020 if (entry.getValue() != null) {
2021 known.add(entry.getKey());
2022 }
2023 }
2024
2025 if (known.size() > 0) {
2026 list = new String[known.size()];
2027 known.toArray(list);
2028 }
2029 return list;
2030 }
2031
2032 // Select which transport to use for the next backup operation. If the given
2033 // name is not one of the available transports, no action is taken and the method
2034 // returns null.
2035 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002037
2038 synchronized (mTransports) {
2039 String prevTransport = null;
2040 if (mTransports.get(transport) != null) {
2041 prevTransport = mCurrentTransport;
2042 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002043 Settings.Secure.putString(mContext.getContentResolver(),
2044 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002045 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2046 + " returning " + prevTransport);
2047 } else {
2048 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2049 }
2050 return prevTransport;
2051 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002052 }
2053
2054 // Callback: a requested backup agent has been instantiated. This should only
2055 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002056 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002057 synchronized(mAgentConnectLock) {
2058 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2059 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2060 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2061 mConnectedAgent = agent;
2062 mConnecting = false;
2063 } else {
2064 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2065 + " claiming agent connected");
2066 }
2067 mAgentConnectLock.notifyAll();
2068 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002069 }
2070
2071 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2072 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002073 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002074 public void agentDisconnected(String packageName) {
2075 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002076 synchronized(mAgentConnectLock) {
2077 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2078 mConnectedAgent = null;
2079 mConnecting = false;
2080 } else {
2081 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2082 + " claiming agent disconnected");
2083 }
2084 mAgentConnectLock.notifyAll();
2085 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002086 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002087
Christopher Tate8c850b72009-06-07 19:33:20 -07002088 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002089 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002091
2092 synchronized(this) {
2093 if (mActiveRestoreSession != null) {
2094 Log.d(TAG, "Restore session requested but one already active");
2095 return null;
2096 }
Christopher Tate91717492009-06-26 21:07:13 -07002097 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002098 }
2099 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002100 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002101
Christopher Tate9b3905c2009-06-08 15:24:01 -07002102 // ----- Restore session -----
2103
2104 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002105 private static final String TAG = "RestoreSession";
2106
Christopher Tate9b3905c2009-06-08 15:24:01 -07002107 private IBackupTransport mRestoreTransport = null;
2108 RestoreSet[] mRestoreSets = null;
2109
Christopher Tate91717492009-06-26 21:07:13 -07002110 RestoreSession(String transport) {
2111 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002112 }
2113
2114 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002115 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002117 "getAvailableRestoreSets");
2118
Christopher Tatef68eb502009-06-16 11:02:01 -07002119 try {
Christopher Tate43383042009-07-13 15:17:13 -07002120 if (mRestoreTransport == null) {
2121 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002122 return null;
2123 }
2124 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002125 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002126 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002127 }
2128 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002129 } catch (Exception e) {
2130 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2131 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002132 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002133 }
2134
Dan Egnor0084da52009-07-29 12:57:16 -07002135 public synchronized int performRestore(long token, IRestoreObserver observer) {
2136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2137 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002138
Christopher Tatef2c321a2009-08-10 15:43:36 -07002139 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2140 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002141
Dan Egnor0084da52009-07-29 12:57:16 -07002142 if (mRestoreTransport == null || mRestoreSets == null) {
2143 Log.e(TAG, "Ignoring performRestore() with no restore set");
2144 return -1;
2145 }
2146
Christopher Tate21ab6a52009-09-24 18:01:46 -07002147 synchronized (mQueueLock) {
2148 if (mBackupOrRestoreInProgress) {
2149 Log.e(TAG, "Backup pass in progress, restore aborted");
2150 return -1;
2151 }
2152
2153 for (int i = 0; i < mRestoreSets.length; i++) {
2154 if (token == mRestoreSets[i].token) {
2155 long oldId = Binder.clearCallingIdentity();
2156 // Suppress backups until the restore operation is finished
2157 mBackupOrRestoreInProgress = true;
2158 mWakelock.acquire();
2159 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2160 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2161 mBackupHandler.sendMessage(msg);
2162 Binder.restoreCallingIdentity(oldId);
2163 return 0;
2164 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002165 }
2166 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002167
2168 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002169 return -1;
2170 }
2171
Dan Egnor0084da52009-07-29 12:57:16 -07002172 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002173 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002174 "endRestoreSession");
2175
Dan Egnor0084da52009-07-29 12:57:16 -07002176 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002177
Dan Egnor0084da52009-07-29 12:57:16 -07002178 synchronized (this) {
2179 try {
2180 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2181 } catch (Exception e) {
2182 Log.e(TAG, "Error in finishRestore", e);
2183 } finally {
2184 mRestoreTransport = null;
2185 }
2186 }
2187
2188 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002189 if (BackupManagerService.this.mActiveRestoreSession == this) {
2190 BackupManagerService.this.mActiveRestoreSession = null;
2191 } else {
2192 Log.e(TAG, "ending non-current restore session");
2193 }
2194 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002195 }
2196 }
2197
Christopher Tate043dadc2009-06-02 16:11:00 -07002198
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002199 @Override
2200 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2201 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002202 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002203 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2204 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2205 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2206 + (!mInitInProgress ? "not " : "") + "initializing");
2207 pw.println("Last backup pass: " + mLastBackupPass
2208 + " (now = " + System.currentTimeMillis() + ')');
2209 pw.println(" next scheduled: " + mNextBackupPass);
2210
Christopher Tate91717492009-06-26 21:07:13 -07002211 pw.println("Available transports:");
2212 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002213 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
2214 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07002215 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002216
2217 pw.println("Pending init: " + mPendingInits.size());
2218 for (String s : mPendingInits) {
2219 pw.println(" " + s);
2220 }
2221
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002222 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002223 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002224 for (int i=0; i<N; i++) {
2225 int uid = mBackupParticipants.keyAt(i);
2226 pw.print(" uid: ");
2227 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002228 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2229 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002230 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002231 }
2232 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002233
Christopher Tate73e02522009-07-15 14:18:26 -07002234 pw.println("Ever backed up: " + mEverStoredApps.size());
2235 for (String pkg : mEverStoredApps) {
2236 pw.println(" " + pkg);
2237 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002238
2239 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002240 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002241 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002242 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002243 }
2244 }
Christopher Tate487529a2009-04-29 14:03:25 -07002245}