blob: c3b591ee64f9cb4dbc904a8689dc987c7ffc642f [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;
Dan Egnorc1c49c02009-10-30 17:35:39 -070079import java.util.Random;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81class BackupManagerService extends IBackupManager.Stub {
82 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070083 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070084
Christopher Tate49401dd2009-07-01 12:34:29 -070085 // How often we perform a backup pass. Privileged external callers can
86 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070087 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070088
Dan Egnorc1c49c02009-10-30 17:35:39 -070089 // Random variation in backup scheduling time to avoid server load spikes
90 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
91
Christopher Tate8031a3d2009-07-06 16:36:05 -070092 // The amount of time between the initial provisioning of the device and
93 // the first backup pass.
94 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
95
Christopher Tate4cc86e12009-09-21 19:36:51 -070096 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
97 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
98 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070099 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700100 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700101 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700102 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700103 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700104
Dan Egnorbb9001c2009-07-27 12:20:13 -0700105 // Event tags -- see system/core/logcat/event-log-tags
106 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
107 private static final int BACKUP_START_EVENT = 2821;
108 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
109 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
110 private static final int BACKUP_PACKAGE_EVENT = 2824;
111 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700112 private static final int BACKUP_RESET_EVENT = 2826;
Dan Egnor726247c2009-09-29 19:12:31 -0700113 private static final int BACKUP_INITIALIZE_EVENT = 2827;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700114
115 private static final int RESTORE_START_EVENT = 2830;
116 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
117 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
118 private static final int RESTORE_PACKAGE_EVENT = 2833;
119 private static final int RESTORE_SUCCESS_EVENT = 2834;
120
Christopher Tatec7b31e32009-06-10 15:49:30 -0700121 // Timeout interval for deciding that a bind or clear-data has taken too long
122 static final long TIMEOUT_INTERVAL = 10 * 1000;
123
Christopher Tate487529a2009-04-29 14:03:25 -0700124 private Context mContext;
125 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700126 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700127 private PowerManager mPowerManager;
128 private AlarmManager mAlarmManager;
129
Christopher Tate73e02522009-07-15 14:18:26 -0700130 boolean mEnabled; // access to this is synchronized on 'this'
131 boolean mProvisioned;
132 PowerManager.WakeLock mWakelock;
133 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700134 PendingIntent mRunBackupIntent, mRunInitIntent;
135 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700136 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700137 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700138 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700139 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700140 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700141 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700142 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700143
Christopher Tate181fafa2009-05-14 11:12:14 -0700144 BackupRequest(ApplicationInfo app, boolean isFull) {
145 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700146 fullBackup = isFull;
147 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700148
149 public String toString() {
150 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
151 }
Christopher Tate46758122009-05-06 11:22:00 -0700152 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400153 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700154 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700155 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700156
157 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700158 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700159
160 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700161 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700162
Christopher Tate043dadc2009-06-02 16:11:00 -0700163 // The thread performing the sequence of queued backups binds to each app's agent
164 // in succession. Bind notifications are asynchronously delivered through the
165 // Activity Manager; use this lock object to signal when a requested binding has
166 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700167 final Object mAgentConnectLock = new Object();
168 IBackupAgent mConnectedAgent;
169 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700170 volatile boolean mBackupOrRestoreInProgress = false;
Christopher Tate55f931a2009-09-29 17:17:34 -0700171 volatile long mLastBackupPass;
172 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700173
Christopher Tate55f931a2009-09-29 17:17:34 -0700174 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700175 final Object mClearDataLock = new Object();
176 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700177
Christopher Tate91717492009-06-26 21:07:13 -0700178 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700179 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700180 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700181 String mCurrentTransport;
182 IBackupTransport mLocalTransport, mGoogleTransport;
183 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700184
Christopher Tate73e02522009-07-15 14:18:26 -0700185 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700186 public IBackupTransport transport;
187 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700188 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700189
Dan Egnor156411d2009-06-26 13:20:02 -0700190 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700191 transport = _transport;
192 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700193 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700194 }
195 }
196
Christopher Tate73e02522009-07-15 14:18:26 -0700197 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700198 public IBackupTransport transport;
199 public PackageInfo packageInfo;
200
201 ClearParams(IBackupTransport _transport, PackageInfo _info) {
202 transport = _transport;
203 packageInfo = _info;
204 }
205 }
206
Christopher Tate5cb400b2009-06-25 16:03:14 -0700207 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700208 File mBaseStateDir;
209 File mDataDir;
210 File mJournalDir;
211 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700212
213 // Keep a log of all the apps we've ever backed up
214 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700215 HashSet<String> mEverStoredApps = new HashSet<String>();
216
Christopher Tate4cc86e12009-09-21 19:36:51 -0700217 // Persistently track the need to do a full init
218 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
219 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700220 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700221
Christopher Tate487529a2009-04-29 14:03:25 -0700222 public BackupManagerService(Context context) {
223 mContext = context;
224 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700225 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700226
Christopher Tateb6787f22009-07-02 17:40:45 -0700227 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
228 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
229
Christopher Tate22b87872009-05-04 16:41:53 -0700230 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700231 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700232 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700233 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700234 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700235 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700236 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700237
Christopher Tate4cc86e12009-09-21 19:36:51 -0700238 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700239 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700240 IntentFilter filter = new IntentFilter();
241 filter.addAction(RUN_BACKUP_ACTION);
242 context.registerReceiver(mRunBackupReceiver, filter,
243 android.Manifest.permission.BACKUP, null);
244
245 mRunInitReceiver = new RunInitializeReceiver();
246 filter = new IntentFilter();
247 filter.addAction(RUN_INITIALIZE_ACTION);
248 context.registerReceiver(mRunInitReceiver, filter,
249 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700250
251 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700252 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
253 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
254
Christopher Tate4cc86e12009-09-21 19:36:51 -0700255 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
256 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
257 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
258
Christopher Tatecde87f42009-06-12 12:55:53 -0700259 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700260 mJournalDir = new File(mBaseStateDir, "pending");
261 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700262 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700263
Christopher Tate73e02522009-07-15 14:18:26 -0700264 // Set up the various sorts of package tracking we do
265 initPackageTracking();
266
Christopher Tateabce4e82009-06-18 18:35:32 -0700267 // Build our mapping of uid to backup client services. This implicitly
268 // schedules a backup pass on the Package Manager metadata the first
269 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700270 synchronized (mBackupParticipants) {
271 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700272 }
273
Dan Egnor87a02bc2009-06-17 02:30:10 -0700274 // Set up our transport options and initialize the default transport
275 // TODO: Have transports register themselves somehow?
276 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700277 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700278 ComponentName localName = new ComponentName(context, LocalTransport.class);
279 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700280
Christopher Tate91717492009-06-26 21:07:13 -0700281 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700282 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
283 Settings.Secure.BACKUP_TRANSPORT);
284 if ("".equals(mCurrentTransport)) {
285 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700286 }
Christopher Tate91717492009-06-26 21:07:13 -0700287 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
288
289 // Attach to the Google backup transport. When this comes up, it will set
290 // itself as the current transport because we explicitly reset mCurrentTransport
291 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700292 Intent intent = new Intent().setComponent(new ComponentName(
293 "com.google.android.backup",
294 "com.google.android.backup.BackupTransportService"));
295 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700296
Christopher Tatecde87f42009-06-12 12:55:53 -0700297 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700298 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700299 parseLeftoverJournals();
300
Christopher Tateb6787f22009-07-02 17:40:45 -0700301 // Power management
302 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
303
304 // Start the backup passes going
305 setBackupEnabled(areEnabled);
306 }
307
308 private class RunBackupReceiver extends BroadcastReceiver {
309 public void onReceive(Context context, Intent intent) {
310 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700311 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700312 if (mPendingInits.size() > 0) {
313 // If there are pending init operations, we process those
314 // and then settle into the usual periodic backup schedule.
315 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
316 try {
317 mAlarmManager.cancel(mRunInitIntent);
318 mRunInitIntent.send();
319 } catch (PendingIntent.CanceledException ce) {
320 Log.e(TAG, "Run init intent cancelled");
321 // can't really do more than bail here
322 }
323 } else {
324 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700325 // fully set up, in the middle of a backup already,
326 // or racing with an initialize pass.
327 if (mEnabled && mProvisioned
328 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700329 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700330 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700331
332 // Acquire the wakelock and pass it to the backup thread. it will
333 // be released once backup concludes.
334 mWakelock.acquire();
335
336 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
337 mBackupHandler.sendMessage(msg);
338 } else {
339 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700340 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700341 }
342 }
343 }
344 }
345 }
346 }
347
348 private class RunInitializeReceiver extends BroadcastReceiver {
349 public void onReceive(Context context, Intent intent) {
350 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
351 synchronized (mQueueLock) {
352 if (DEBUG) Log.v(TAG, "Running a device init");
353 mInitInProgress = true;
354
355 // Acquire the wakelock and pass it to the init thread. it will
356 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700357 mWakelock.acquire();
358
Christopher Tate4cc86e12009-09-21 19:36:51 -0700359 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700360 mBackupHandler.sendMessage(msg);
361 }
362 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700363 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700364 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700365
Christopher Tate73e02522009-07-15 14:18:26 -0700366 private void initPackageTracking() {
367 if (DEBUG) Log.v(TAG, "Initializing package tracking");
368
Christopher Tatee97e8072009-07-15 16:45:50 -0700369 // Keep a log of what apps we've ever backed up. Because we might have
370 // rebooted in the middle of an operation that was removing something from
371 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700372 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700373 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700374
Christopher Tatee97e8072009-07-15 16:45:50 -0700375 // If we were in the middle of removing something from the ever-backed-up
376 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700377 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700378 if (tempProcessedFile.exists()) {
379 tempProcessedFile.delete();
380 }
381
Dan Egnor852f8e42009-09-30 11:20:45 -0700382 // If there are previous contents, parse them out then start a new
383 // file to continue the recordkeeping.
384 if (mEverStored.exists()) {
385 RandomAccessFile temp = null;
386 RandomAccessFile in = null;
387
388 try {
389 temp = new RandomAccessFile(tempProcessedFile, "rws");
390 in = new RandomAccessFile(mEverStored, "r");
391
392 while (true) {
393 PackageInfo info;
394 String pkg = in.readUTF();
395 try {
396 info = mPackageManager.getPackageInfo(pkg, 0);
397 mEverStoredApps.add(pkg);
398 temp.writeUTF(pkg);
399 if (DEBUG) Log.v(TAG, " + " + pkg);
400 } catch (NameNotFoundException e) {
401 // nope, this package was uninstalled; don't include it
402 if (DEBUG) Log.v(TAG, " - " + pkg);
403 }
404 }
405 } catch (EOFException e) {
406 // Once we've rewritten the backup history log, atomically replace the
407 // old one with the new one then reopen the file for continuing use.
408 if (!tempProcessedFile.renameTo(mEverStored)) {
409 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
410 }
411 } catch (IOException e) {
412 Log.e(TAG, "Error in processed file", e);
413 } finally {
414 try { if (temp != null) temp.close(); } catch (IOException e) {}
415 try { if (in != null) in.close(); } catch (IOException e) {}
416 }
417 }
418
Christopher Tate73e02522009-07-15 14:18:26 -0700419 // Register for broadcasts about package install, etc., so we can
420 // update the provider list.
421 IntentFilter filter = new IntentFilter();
422 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
423 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
424 filter.addDataScheme("package");
425 mContext.registerReceiver(mBroadcastReceiver, filter);
426 }
427
Christopher Tatecde87f42009-06-12 12:55:53 -0700428 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700429 for (File f : mJournalDir.listFiles()) {
430 if (mJournal == null || f.compareTo(mJournal) != 0) {
431 // This isn't the current journal, so it must be a leftover. Read
432 // out the package names mentioned there and schedule them for
433 // backup.
434 RandomAccessFile in = null;
435 try {
436 Log.i(TAG, "Found stale backup journal, scheduling:");
437 in = new RandomAccessFile(f, "r");
438 while (true) {
439 String packageName = in.readUTF();
440 Log.i(TAG, " + " + packageName);
441 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700442 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700443 } catch (EOFException e) {
444 // no more data; we're done
445 } catch (Exception e) {
446 Log.e(TAG, "Can't read " + f, e);
447 } finally {
448 // close/delete the file
449 try { if (in != null) in.close(); } catch (IOException e) {}
450 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700451 }
452 }
453 }
454 }
455
Christopher Tate4cc86e12009-09-21 19:36:51 -0700456 // Maintain persistent state around whether need to do an initialize operation.
457 // Must be called with the queue lock held.
458 void recordInitPendingLocked(boolean isPending, String transportName) {
459 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
460 + " on transport " + transportName);
461 try {
462 IBackupTransport transport = getTransport(transportName);
463 String transportDirName = transport.transportDirName();
464 File stateDir = new File(mBaseStateDir, transportDirName);
465 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
466
467 if (isPending) {
468 // We need an init before we can proceed with sending backup data.
469 // Record that with an entry in our set of pending inits, as well as
470 // journaling it via creation of a sentinel file.
471 mPendingInits.add(transportName);
472 try {
473 (new FileOutputStream(initPendingFile)).close();
474 } catch (IOException ioe) {
475 // Something is badly wrong with our permissions; just try to move on
476 }
477 } else {
478 // No more initialization needed; wipe the journal and reset our state.
479 initPendingFile.delete();
480 mPendingInits.remove(transportName);
481 }
482 } catch (RemoteException e) {
483 // can't happen; the transport is local
484 }
485 }
486
Christopher Tated55e18a2009-09-21 10:12:59 -0700487 // Reset all of our bookkeeping, in response to having been told that
488 // the backend data has been wiped [due to idle expiry, for example],
489 // so we must re-upload all saved settings.
490 void resetBackupState(File stateFileDir) {
491 synchronized (mQueueLock) {
492 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700493 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700494 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700495
496 // Remove all the state files
497 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700498 // ... but don't touch the needs-init sentinel
499 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
500 sf.delete();
501 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700502 }
503
504 // Enqueue a new backup of every participant
505 int N = mBackupParticipants.size();
506 for (int i=0; i<N; i++) {
507 int uid = mBackupParticipants.keyAt(i);
508 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
509 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700510 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700511 }
512 }
513 }
514 }
515
Christopher Tate91717492009-06-26 21:07:13 -0700516 // Add a transport to our set of available backends
517 private void registerTransport(String name, IBackupTransport transport) {
518 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700519 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700520 mTransports.put(name, transport);
521 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700522
523 // If the init sentinel file exists, we need to be sure to perform the init
524 // as soon as practical. We also create the state directory at registration
525 // time to ensure it's present from the outset.
526 try {
527 String transportName = transport.transportDirName();
528 File stateDir = new File(mBaseStateDir, transportName);
529 stateDir.mkdirs();
530
531 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
532 if (initSentinel.exists()) {
533 synchronized (mQueueLock) {
534 mPendingInits.add(transportName);
535
536 // TODO: pick a better starting time than now + 1 minute
537 long delay = 1000 * 60; // one minute, in milliseconds
538 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
539 System.currentTimeMillis() + delay, mRunInitIntent);
540 }
541 }
542 } catch (RemoteException e) {
543 // can't happen, the transport is local
544 }
Christopher Tate91717492009-06-26 21:07:13 -0700545 }
546
Christopher Tate3799bc22009-05-06 16:13:56 -0700547 // ----- Track installation/removal of packages -----
548 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
549 public void onReceive(Context context, Intent intent) {
550 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
551
552 Uri uri = intent.getData();
553 if (uri == null) {
554 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700555 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700556 String pkgName = uri.getSchemeSpecificPart();
557 if (pkgName == null) {
558 return;
559 }
560
561 String action = intent.getAction();
562 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
563 synchronized (mBackupParticipants) {
564 Bundle extras = intent.getExtras();
565 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
566 // The package was just upgraded
567 updatePackageParticipantsLocked(pkgName);
568 } else {
569 // The package was just added
570 addPackageParticipantsLocked(pkgName);
571 }
572 }
573 }
574 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
575 Bundle extras = intent.getExtras();
576 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
577 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
578 } else {
579 synchronized (mBackupParticipants) {
580 removePackageParticipantsLocked(pkgName);
581 }
582 }
583 }
584 }
585 };
586
Dan Egnor87a02bc2009-06-17 02:30:10 -0700587 // ----- Track connection to GoogleBackupTransport service -----
588 ServiceConnection mGoogleConnection = new ServiceConnection() {
589 public void onServiceConnected(ComponentName name, IBinder service) {
590 if (DEBUG) Log.v(TAG, "Connected to Google transport");
591 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700592 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700593 }
594
595 public void onServiceDisconnected(ComponentName name) {
596 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
597 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700598 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700599 }
600 };
601
Joe Onorato8ad02812009-05-13 01:41:44 -0400602 // ----- Run the actual backup process asynchronously -----
603
Christopher Tate181fafa2009-05-14 11:12:14 -0700604 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400605 public void handleMessage(Message msg) {
606
607 switch (msg.what) {
608 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700609 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700610 mLastBackupPass = System.currentTimeMillis();
611 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
612
Christopher Tate91717492009-06-26 21:07:13 -0700613 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700614 if (transport == null) {
615 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700616 synchronized (mQueueLock) {
617 mBackupOrRestoreInProgress = false;
618 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700619 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700620 break;
621 }
622
Joe Onorato8ad02812009-05-13 01:41:44 -0400623 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700624 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400625 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700626 // Do we have any work to do?
627 if (mPendingBackups.size() > 0) {
628 for (BackupRequest b: mPendingBackups.values()) {
629 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700630 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700631 Log.v(TAG, "clearing pending backups");
632 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700633
Christopher Tate49401dd2009-07-01 12:34:29 -0700634 // Start a new backup-queue journal file too
Dan Egnor852f8e42009-09-30 11:20:45 -0700635 File oldJournal = mJournal;
636 mJournal = null;
Christopher Tate49401dd2009-07-01 12:34:29 -0700637
638 // At this point, we have started a new journal file, and the old
639 // file identity is being passed to the backup processing thread.
640 // When it completes successfully, that old journal file will be
641 // deleted. If we crash prior to that, the old journal is parsed
642 // at next boot and the journaled requests fulfilled.
643 (new PerformBackupThread(transport, queue, oldJournal)).start();
644 } else {
645 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700646 synchronized (mQueueLock) {
647 mBackupOrRestoreInProgress = false;
648 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700649 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700650 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400651 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700652 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700653 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700654
655 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400656 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700657
658 case MSG_RUN_RESTORE:
659 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700660 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400661 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700662 (new PerformRestoreThread(params.transport, params.observer,
663 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700664 break;
665 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700666
667 case MSG_RUN_CLEAR:
668 {
669 ClearParams params = (ClearParams)msg.obj;
670 (new PerformClearThread(params.transport, params.packageInfo)).start();
671 break;
672 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700673
674 case MSG_RUN_INITIALIZE:
675 {
676 HashSet<String> queue;
677
678 // Snapshot the pending-init queue and work on that
679 synchronized (mQueueLock) {
680 queue = new HashSet<String>(mPendingInits);
681 mPendingInits.clear();
682 }
683
684 (new PerformInitializeThread(queue)).start();
685 break;
686 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400687 }
688 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400689 }
690
Christopher Tate181fafa2009-05-14 11:12:14 -0700691 // Add the backup agents in the given package to our set of known backup participants.
692 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700693 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700694 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700695 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700696 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700697 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700698 }
699
Christopher Tate181fafa2009-05-14 11:12:14 -0700700 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700701 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700702 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700703 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
704 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700705 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700706 + " uid=" + p.applicationInfo.uid
707 + " killAfterRestore="
708 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
709 + " restoreNeedsApplication="
710 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
711 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700712 }
713 }
714
Dan Egnorefe52642009-06-24 00:16:33 -0700715 for (PackageInfo pkg : targetPkgs) {
716 if (packageName == null || pkg.packageName.equals(packageName)) {
717 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700718 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700719 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700720 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700721 mBackupParticipants.put(uid, set);
722 }
Dan Egnorefe52642009-06-24 00:16:33 -0700723 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700724
725 // If we've never seen this app before, schedule a backup for it
726 if (!mEverStoredApps.contains(pkg.packageName)) {
727 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
728 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700729 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700730 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700731 }
Christopher Tate487529a2009-04-29 14:03:25 -0700732 }
733 }
734
Christopher Tate6785dd82009-06-18 15:58:25 -0700735 // Remove the given package's entry from our known active set. If
736 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700737 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700738 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700739 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700740 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700741 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700742 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700743 int flags = PackageManager.GET_SIGNATURES;
744 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700745 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700746 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700747 }
748 } else {
749 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700750 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700751 }
752 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700753 }
754
Joe Onorato8ad02812009-05-13 01:41:44 -0400755 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700756 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700757 if (DEBUG) {
758 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
759 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700760 for (PackageInfo p : agents) {
761 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700762 }
763 }
Dan Egnorefe52642009-06-24 00:16:33 -0700764 for (PackageInfo pkg : agents) {
765 if (packageName == null || pkg.packageName.equals(packageName)) {
766 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700767 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700768 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700769 // Find the existing entry with the same package name, and remove it.
770 // We can't just remove(app) because the instances are different.
771 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700772 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700773 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700774 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700775 break;
776 }
777 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700778 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700779 mBackupParticipants.delete(uid);
780 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700781 }
782 }
783 }
784 }
785
Christopher Tate181fafa2009-05-14 11:12:14 -0700786 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700787 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700788 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700789 int flags = PackageManager.GET_SIGNATURES;
790 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
791 int N = packages.size();
792 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700793 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700794 try {
795 ApplicationInfo app = pkg.applicationInfo;
796 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
797 || app.backupAgentName == null
798 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
799 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
800 packages.remove(a);
801 }
802 else {
803 // we will need the shared library path, so look that up and store it here
804 app = mPackageManager.getApplicationInfo(pkg.packageName,
805 PackageManager.GET_SHARED_LIBRARY_FILES);
806 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
807 }
808 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700809 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700810 }
811 }
Dan Egnorefe52642009-06-24 00:16:33 -0700812 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700813 }
Christopher Tateaa088442009-06-16 18:25:46 -0700814
Christopher Tate3799bc22009-05-06 16:13:56 -0700815 // Reset the given package's known backup participants. Unlike add/remove, the update
816 // action cannot be passed a null package name.
817 void updatePackageParticipantsLocked(String packageName) {
818 if (packageName == null) {
819 Log.e(TAG, "updatePackageParticipants called with null package name");
820 return;
821 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700822 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700823
824 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700825 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700826 removePackageParticipantsLockedInner(packageName, allApps);
827 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700828 }
829
Christopher Tate73e02522009-07-15 14:18:26 -0700830 // Called from the backup thread: record that the given app has been successfully
831 // backed up at least once
832 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700833 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
834
835 synchronized (mEverStoredApps) {
836 if (!mEverStoredApps.add(packageName)) return;
837
838 RandomAccessFile out = null;
839 try {
840 out = new RandomAccessFile(mEverStored, "rws");
841 out.seek(out.length());
842 out.writeUTF(packageName);
843 } catch (IOException e) {
844 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
845 } finally {
846 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700847 }
848 }
849 }
850
Christopher Tatee97e8072009-07-15 16:45:50 -0700851 // Remove our awareness of having ever backed up the given package
852 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700853 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700854
Dan Egnor852f8e42009-09-30 11:20:45 -0700855 synchronized (mEverStoredApps) {
856 // Rewrite the file and rename to overwrite. If we reboot in the middle,
857 // we'll recognize on initialization time that the package no longer
858 // exists and fix it up then.
859 File tempKnownFile = new File(mBaseStateDir, "processed.new");
860 RandomAccessFile known = null;
861 try {
862 known = new RandomAccessFile(tempKnownFile, "rws");
863 mEverStoredApps.remove(packageName);
864 for (String s : mEverStoredApps) {
865 known.writeUTF(s);
866 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700867 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700868 known.close();
869 known = null;
870 if (!tempKnownFile.renameTo(mEverStored)) {
871 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
872 }
873 } catch (IOException e) {
874 // Bad: we couldn't create the new copy. For safety's sake we
875 // abandon the whole process and remove all what's-backed-up
876 // state entirely, meaning we'll force a backup pass for every
877 // participant on the next boot or [re]install.
878 Log.w(TAG, "Error rewriting " + mEverStored, e);
879 mEverStoredApps.clear();
880 tempKnownFile.delete();
881 mEverStored.delete();
882 } finally {
883 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700884 }
885 }
886 }
887
Dan Egnor87a02bc2009-06-17 02:30:10 -0700888 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700889 private IBackupTransport getTransport(String transportName) {
890 synchronized (mTransports) {
891 IBackupTransport transport = mTransports.get(transportName);
892 if (transport == null) {
893 Log.w(TAG, "Requested unavailable transport: " + transportName);
894 }
895 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700896 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700897 }
898
Christopher Tatedf01dea2009-06-09 20:45:02 -0700899 // fire off a backup agent, blocking until it attaches or times out
900 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
901 IBackupAgent agent = null;
902 synchronized(mAgentConnectLock) {
903 mConnecting = true;
904 mConnectedAgent = null;
905 try {
906 if (mActivityManager.bindBackupAgent(app, mode)) {
907 Log.d(TAG, "awaiting agent for " + app);
908
909 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700910 // only wait 10 seconds for the clear data to happen
911 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
912 while (mConnecting && mConnectedAgent == null
913 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700914 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700915 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700916 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700917 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700918 return null;
919 }
920 }
921
922 // if we timed out with no connect, abort and move on
923 if (mConnecting == true) {
924 Log.w(TAG, "Timeout waiting for agent " + app);
925 return null;
926 }
927 agent = mConnectedAgent;
928 }
929 } catch (RemoteException e) {
930 // can't happen
931 }
932 }
933 return agent;
934 }
935
Christopher Tatec7b31e32009-06-10 15:49:30 -0700936 // clear an application's data, blocking until the operation completes or times out
937 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700938 // Don't wipe packages marked allowClearUserData=false
939 try {
940 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
941 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
942 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
943 + packageName);
944 return;
945 }
946 } catch (NameNotFoundException e) {
947 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
948 return;
949 }
950
Christopher Tatec7b31e32009-06-10 15:49:30 -0700951 ClearDataObserver observer = new ClearDataObserver();
952
953 synchronized(mClearDataLock) {
954 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700955 /* This is causing some critical processes to be killed during setup.
956 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700957 try {
958 mActivityManager.clearApplicationUserData(packageName, observer);
959 } catch (RemoteException e) {
960 // can't happen because the activity manager is in this process
961 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700962 */
963 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700964
965 // only wait 10 seconds for the clear data to happen
966 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
967 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
968 try {
969 mClearDataLock.wait(5000);
970 } catch (InterruptedException e) {
971 // won't happen, but still.
972 mClearingData = false;
973 }
974 }
975 }
976 }
977
978 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -0700979 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700980 synchronized(mClearDataLock) {
981 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700982 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700983 }
984 }
985 }
986
Christopher Tate043dadc2009-06-02 16:11:00 -0700987 // ----- Back up a set of applications via a worker thread -----
988
989 class PerformBackupThread extends Thread {
990 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700991 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700992 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700993 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700994 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700995
Christopher Tateaa088442009-06-16 18:25:46 -0700996 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700997 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700998 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700999 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001000 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001001
1002 try {
1003 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1004 } catch (RemoteException e) {
1005 // can't happen; the transport is local
1006 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001007 }
1008
1009 @Override
1010 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001011 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001012 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001013 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1014
Christopher Tate79588342009-06-30 16:11:49 -07001015 // Backups run at background priority
1016 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1017
Christopher Tate043dadc2009-06-02 16:11:00 -07001018 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001019 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001020
Dan Egnor852f8e42009-09-30 11:20:45 -07001021 // If we haven't stored package manager metadata yet, we must init the transport.
1022 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1023 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1024 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1025 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001026 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001027 if (status == BackupConstants.TRANSPORT_OK) {
1028 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1029 } else {
1030 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
1031 Log.e(TAG, "Transport error in initializeDevice()");
1032 }
Dan Egnor01445162009-09-21 17:04:05 -07001033 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001034
1035 // The package manager doesn't have a proper <application> etc, but since
1036 // it's running here in the system process we can just set up its agent
1037 // directly and use a synthetic BackupRequest. We always run this pass
1038 // because it's cheap and this way we guarantee that we don't get out of
1039 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001040 if (status == BackupConstants.TRANSPORT_OK) {
1041 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1042 mPackageManager, allAgentPackages());
1043 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1044 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1045 status = processOneBackup(pmRequest,
1046 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1047 }
Christopher Tate90967f42009-09-20 15:28:33 -07001048
Dan Egnor01445162009-09-21 17:04:05 -07001049 if (status == BackupConstants.TRANSPORT_OK) {
1050 // Now run all the backups in our queue
1051 status = doQueuedBackups(mTransport);
1052 }
1053
1054 if (status == BackupConstants.TRANSPORT_OK) {
1055 // Tell the transport to finish everything it has buffered
1056 status = mTransport.finishBackup();
1057 if (status == BackupConstants.TRANSPORT_OK) {
1058 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1059 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1060 } else {
Dan Egnor726247c2009-09-29 19:12:31 -07001061 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001062 Log.e(TAG, "Transport error in finishBackup()");
1063 }
1064 }
1065
Dan Egnor01445162009-09-21 17:04:05 -07001066 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001067 // The backend reports that our dataset has been wiped. We need to
1068 // reset all of our bookkeeping and instead run a new backup pass for
Dan Egnor852f8e42009-09-30 11:20:45 -07001069 // everything. This must come after mBackupOrRestoreInProgress is cleared.
Christopher Tated55e18a2009-09-21 10:12:59 -07001070 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1071 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001072 }
1073 } catch (Exception e) {
1074 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001075 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001076 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001077 // If things went wrong, we need to re-stage the apps we had expected
1078 // to be backing up in this pass. This journals the package names in
1079 // the current active pending-backup file, not in the we are holding
1080 // here in mJournal.
1081 if (status != BackupConstants.TRANSPORT_OK) {
1082 Log.w(TAG, "Backup pass unsuccessful, restaging");
1083 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001084 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001085 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001086
1087 // We also want to reset the backup schedule based on whatever
1088 // the transport suggests by way of retry/backoff time.
1089 try {
1090 startBackupAlarmsLocked(mTransport.requestBackupTime());
1091 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001092 }
1093
1094 // Either backup was successful, in which case we of course do not need
1095 // this pass's journal any more; or it failed, in which case we just
1096 // re-enqueued all of these packages in the current active journal.
1097 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001098 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001099 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1100 }
1101
Christopher Tate21ab6a52009-09-24 18:01:46 -07001102 // Only once we're entirely finished do we indicate our completion
1103 // and release the wakelock
1104 synchronized (mQueueLock) {
1105 mBackupOrRestoreInProgress = false;
1106 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001107
1108 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1109 // This must come after mBackupOrRestoreInProgress is cleared.
1110 backupNow();
1111 }
1112
Dan Egnorbb9001c2009-07-27 12:20:13 -07001113 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001114 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001115 }
1116
Dan Egnor01445162009-09-21 17:04:05 -07001117 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001118 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001119 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001120
Christopher Tate0749dcd2009-08-13 15:13:03 -07001121 // Don't run backup, even if requested, if the target app does not have
1122 // the requisite permission
1123 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1124 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1125 Log.w(TAG, "Skipping backup of unprivileged package "
1126 + request.appInfo.packageName);
1127 continue;
1128 }
1129
Christopher Tate043dadc2009-06-02 16:11:00 -07001130 IBackupAgent agent = null;
1131 int mode = (request.fullBackup)
1132 ? IApplicationThread.BACKUP_MODE_FULL
1133 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1134 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001135 agent = bindToAgentSynchronous(request.appInfo, mode);
1136 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001137 int result = processOneBackup(request, agent, transport);
1138 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001139 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001140 } catch (SecurityException ex) {
1141 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001142 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001143 } finally {
1144 try { // unbind even on timeout, just in case
1145 mActivityManager.unbindBackupAgent(request.appInfo);
1146 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001147 }
1148 }
Dan Egnor01445162009-09-21 17:04:05 -07001149
1150 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001151 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001152
Dan Egnor01445162009-09-21 17:04:05 -07001153 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1154 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001155 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001156 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001157
Dan Egnorbb9001c2009-07-27 12:20:13 -07001158 File savedStateName = new File(mStateDir, packageName);
1159 File backupDataName = new File(mDataDir, packageName + ".data");
1160 File newStateName = new File(mStateDir, packageName + ".new");
1161
1162 ParcelFileDescriptor savedState = null;
1163 ParcelFileDescriptor backupData = null;
1164 ParcelFileDescriptor newState = null;
1165
1166 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001167 try {
1168 // Look up the package info & signatures. This is first so that if it
1169 // throws an exception, there's no file setup yet that would need to
1170 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001171 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1172 // The metadata 'package' is synthetic
1173 packInfo = new PackageInfo();
1174 packInfo.packageName = packageName;
1175 } else {
1176 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001177 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001178 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001179
Christopher Tatec7b31e32009-06-10 15:49:30 -07001180 // In a full backup, we pass a null ParcelFileDescriptor as
1181 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001182 if (!request.fullBackup) {
1183 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001184 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001185 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1186 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001187
Dan Egnorbb9001c2009-07-27 12:20:13 -07001188 backupData = ParcelFileDescriptor.open(backupDataName,
1189 ParcelFileDescriptor.MODE_READ_WRITE |
1190 ParcelFileDescriptor.MODE_CREATE |
1191 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001192
Dan Egnorbb9001c2009-07-27 12:20:13 -07001193 newState = ParcelFileDescriptor.open(newStateName,
1194 ParcelFileDescriptor.MODE_READ_WRITE |
1195 ParcelFileDescriptor.MODE_CREATE |
1196 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001197
1198 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001199 agent.doBackup(savedState, backupData, newState);
1200 logBackupComplete(packageName);
1201 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001202 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001203 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001204 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1205 backupDataName.delete();
1206 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001207 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001208 } finally {
1209 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1210 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1211 try { if (newState != null) newState.close(); } catch (IOException e) {}
1212 savedState = backupData = newState = null;
1213 }
1214
1215 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001216 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001217 try {
1218 int size = (int) backupDataName.length();
1219 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001220 if (result == BackupConstants.TRANSPORT_OK) {
1221 backupData = ParcelFileDescriptor.open(backupDataName,
1222 ParcelFileDescriptor.MODE_READ_ONLY);
1223 result = transport.performBackup(packInfo, backupData);
1224 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001225
Dan Egnor83861e72009-09-17 16:17:55 -07001226 // TODO - We call finishBackup() for each application backed up, because
1227 // we need to know now whether it succeeded or failed. Instead, we should
1228 // hold off on finishBackup() until the end, which implies holding off on
1229 // renaming *all* the output state files (see below) until that happens.
1230
Dan Egnor01445162009-09-21 17:04:05 -07001231 if (result == BackupConstants.TRANSPORT_OK) {
1232 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001233 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001234 } else {
1235 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1236 }
1237
1238 // After successful transport, delete the now-stale data
1239 // and juggle the files so that next time we supply the agent
1240 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001241 if (result == BackupConstants.TRANSPORT_OK) {
1242 backupDataName.delete();
1243 newStateName.renameTo(savedStateName);
1244 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1245 } else {
1246 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1247 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001248 } catch (Exception e) {
1249 Log.e(TAG, "Transport error backing up " + packageName, e);
1250 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001251 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001252 } finally {
1253 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001254 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001255
Dan Egnor01445162009-09-21 17:04:05 -07001256 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001257 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001258 }
1259
Christopher Tatedf01dea2009-06-09 20:45:02 -07001260
1261 // ----- Restore handling -----
1262
Christopher Tate78dd4a72009-11-04 11:49:08 -08001263 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1264 // If the target resides on the system partition, we allow it to restore
1265 // data from the like-named package in a restore set even if the signatures
1266 // do not match. (Unlike general applications, those flashed to the system
1267 // partition will be signed with the device's platform certificate, so on
1268 // different phones the same system app will have different signatures.)
1269 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1270 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1271 return true;
1272 }
1273
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001274 // Allow unsigned apps, but not signed on one device and unsigned on the other
1275 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001276 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001277 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1278 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001279 if ((storedSigs == null || storedSigs.length == 0)
1280 && (deviceSigs == null || deviceSigs.length == 0)) {
1281 return true;
1282 }
1283 if (storedSigs == null || deviceSigs == null) {
1284 return false;
1285 }
1286
Christopher Tateabce4e82009-06-18 18:35:32 -07001287 // !!! TODO: this demands that every stored signature match one
1288 // that is present on device, and does not demand the converse.
1289 // Is this this right policy?
1290 int nStored = storedSigs.length;
1291 int nDevice = deviceSigs.length;
1292
1293 for (int i=0; i < nStored; i++) {
1294 boolean match = false;
1295 for (int j=0; j < nDevice; j++) {
1296 if (storedSigs[i].equals(deviceSigs[j])) {
1297 match = true;
1298 break;
1299 }
1300 }
1301 if (!match) {
1302 return false;
1303 }
1304 }
1305 return true;
1306 }
1307
Christopher Tatedf01dea2009-06-09 20:45:02 -07001308 class PerformRestoreThread extends Thread {
1309 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001310 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001311 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001312 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001313
Christopher Tate5cbbf562009-06-22 16:44:51 -07001314 class RestoreRequest {
1315 public PackageInfo app;
1316 public int storedAppVersion;
1317
1318 RestoreRequest(PackageInfo _app, int _version) {
1319 app = _app;
1320 storedAppVersion = _version;
1321 }
1322 }
1323
Christopher Tate7d562ec2009-06-25 18:03:43 -07001324 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001325 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001326 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001327 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001328 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001329 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001330
1331 try {
1332 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1333 } catch (RemoteException e) {
1334 // can't happen; the transport is local
1335 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001336 }
1337
1338 @Override
1339 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001340 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001341 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001342 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001343 /**
1344 * Restore sequence:
1345 *
Dan Egnorefe52642009-06-24 00:16:33 -07001346 * 1. get the restore set description for our identity
1347 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001348 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001349 * 3. for each app in the restore queue:
1350 * 3.a. clear the app data
1351 * 3.b. get the restore data for the app from the transport
1352 * 3.c. launch the backup agent for the app
1353 * 3.d. agent.doRestore() with the data from the server
1354 * 3.e. unbind the agent [and kill the app?]
1355 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001356 *
1357 * On errors, we try our best to recover and move on to the next
1358 * application, but if necessary we abort the whole operation --
1359 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001360 */
1361
Christopher Tate7d562ec2009-06-25 18:03:43 -07001362 int error = -1; // assume error
1363
Dan Egnorefe52642009-06-24 00:16:33 -07001364 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001365 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001366 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001367 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001368
Dan Egnorefe52642009-06-24 00:16:33 -07001369 // Get the list of all packages which have backup enabled.
1370 // (Include the Package Manager metadata pseudo-package first.)
1371 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1372 PackageInfo omPackage = new PackageInfo();
1373 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1374 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001375
Dan Egnorefe52642009-06-24 00:16:33 -07001376 List<PackageInfo> agentPackages = allAgentPackages();
1377 restorePackages.addAll(agentPackages);
1378
Christopher Tate7d562ec2009-06-25 18:03:43 -07001379 // let the observer know that we're running
1380 if (mObserver != null) {
1381 try {
1382 // !!! TODO: get an actual count from the transport after
1383 // its startRestore() runs?
1384 mObserver.restoreStarting(restorePackages.size());
1385 } catch (RemoteException e) {
1386 Log.d(TAG, "Restore observer died at restoreStarting");
1387 mObserver = null;
1388 }
1389 }
1390
Dan Egnor01445162009-09-21 17:04:05 -07001391 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1392 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001393 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001394 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001395 return;
1396 }
1397
1398 String packageName = mTransport.nextRestorePackage();
1399 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001400 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001401 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001402 return;
1403 } else if (packageName.equals("")) {
1404 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001405 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1406 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001407 return;
1408 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1409 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1410 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001411 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1412 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001413 return;
1414 }
1415
1416 // Pull the Package Manager metadata from the restore set first
1417 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1418 mPackageManager, agentPackages);
1419 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1420
Christopher Tate8c032472009-07-02 14:28:47 -07001421 // Verify that the backup set includes metadata. If not, we can't do
1422 // signature/version verification etc, so we simply do not proceed with
1423 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001424 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 Log.e(TAG, "No restore metadata available, so not restoring settings");
1426 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1427 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001428 return;
1429 }
1430
Christopher Tate7d562ec2009-06-25 18:03:43 -07001431 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001432 for (;;) {
1433 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434
Dan Egnorefe52642009-06-24 00:16:33 -07001435 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001436 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001437 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001438 return;
1439 } else if (packageName.equals("")) {
1440 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001441 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001442
Christopher Tate7d562ec2009-06-25 18:03:43 -07001443 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001444 try {
1445 mObserver.onUpdate(count);
1446 } catch (RemoteException e) {
1447 Log.d(TAG, "Restore observer died in onUpdate");
1448 mObserver = null;
1449 }
1450 }
1451
Dan Egnorefe52642009-06-24 00:16:33 -07001452 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1453 if (metaInfo == null) {
1454 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001455 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1456 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001457 continue;
1458 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001459
Dan Egnorbb9001c2009-07-27 12:20:13 -07001460 PackageInfo packageInfo;
1461 try {
1462 int flags = PackageManager.GET_SIGNATURES;
1463 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1464 } catch (NameNotFoundException e) {
1465 Log.e(TAG, "Invalid package restoring data", e);
1466 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1467 "Package missing on device");
1468 continue;
1469 }
1470
Dan Egnorefe52642009-06-24 00:16:33 -07001471 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001472 String message = "Version " + metaInfo.versionCode
1473 + " > installed version " + packageInfo.versionCode;
1474 Log.w(TAG, "Package " + packageName + ": " + message);
1475 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001476 continue;
1477 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001478
Christopher Tate78dd4a72009-11-04 11:49:08 -08001479 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001480 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001481 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1482 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001483 continue;
1484 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001485
Dan Egnorefe52642009-06-24 00:16:33 -07001486 if (DEBUG) Log.v(TAG, "Package " + packageName
1487 + " restore version [" + metaInfo.versionCode
1488 + "] is compatible with installed version ["
1489 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001490
Christopher Tate5e1ab332009-09-01 20:32:49 -07001491 // Now perform the actual restore: first clear the app's data
1492 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001493 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001494
1495 // Then set up and bind the agent (with a restricted Application object
1496 // unless the application says otherwise)
1497 boolean useRealApp = (packageInfo.applicationInfo.flags
1498 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1499 if (DEBUG && useRealApp) {
1500 Log.v(TAG, "agent requires real Application subclass for restore");
1501 }
Dan Egnorefe52642009-06-24 00:16:33 -07001502 IBackupAgent agent = bindToAgentSynchronous(
1503 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001504 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1505 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001506 if (agent == null) {
1507 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001508 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1509 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001510 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001511 }
1512
Christopher Tate5e1ab332009-09-01 20:32:49 -07001513 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001514 try {
1515 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001516 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001517 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001518 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001519 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001520
1521 // The agent was probably running with a stub Application object,
1522 // which isn't a valid run mode for the main app logic. Shut
1523 // down the app so that next time it's launched, it gets the
1524 // usual full initialization.
1525 if ((packageInfo.applicationInfo.flags
1526 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1527 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1528 + packageInfo.applicationInfo.processName);
1529 mActivityManager.killApplicationProcess(
1530 packageInfo.applicationInfo.processName,
1531 packageInfo.applicationInfo.uid);
1532 }
Dan Egnorefe52642009-06-24 00:16:33 -07001533 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001534 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001535
1536 // if we get this far, report success to the observer
1537 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001538 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1539 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1540 } catch (Exception e) {
1541 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001542 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001543 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1544
Dan Egnorefe52642009-06-24 00:16:33 -07001545 try {
1546 mTransport.finishRestore();
1547 } catch (RemoteException e) {
1548 Log.e(TAG, "Error finishing restore", e);
1549 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001550
1551 if (mObserver != null) {
1552 try {
1553 mObserver.restoreFinished(error);
1554 } catch (RemoteException e) {
1555 Log.d(TAG, "Restore observer died at restoreFinished");
1556 }
1557 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001558
1559 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001560 synchronized (mQueueLock) {
1561 mBackupOrRestoreInProgress = false;
1562 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001563 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001564 }
1565 }
1566
Dan Egnorefe52642009-06-24 00:16:33 -07001567 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1568 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001569 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001570 final String packageName = app.packageName;
1571
Dan Egnorbb9001c2009-07-27 12:20:13 -07001572 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001573
Christopher Tate0749dcd2009-08-13 15:13:03 -07001574 // Don't restore to unprivileged packages
1575 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1576 packageName) != PackageManager.PERMISSION_GRANTED) {
1577 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1578 }
1579
Christopher Tatec7b31e32009-06-10 15:49:30 -07001580 // !!! TODO: get the dirs from the transport
1581 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001582 File newStateName = new File(mStateDir, packageName + ".new");
1583 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001584
Dan Egnorbb9001c2009-07-27 12:20:13 -07001585 ParcelFileDescriptor backupData = null;
1586 ParcelFileDescriptor newState = null;
1587
1588 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001589 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001590 backupData = ParcelFileDescriptor.open(backupDataName,
1591 ParcelFileDescriptor.MODE_READ_WRITE |
1592 ParcelFileDescriptor.MODE_CREATE |
1593 ParcelFileDescriptor.MODE_TRUNCATE);
1594
Dan Egnor01445162009-09-21 17:04:05 -07001595 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001596 Log.e(TAG, "Error getting restore data for " + packageName);
1597 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1598 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001599 }
1600
1601 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001602 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001603 backupData = ParcelFileDescriptor.open(backupDataName,
1604 ParcelFileDescriptor.MODE_READ_ONLY);
1605
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 newState = ParcelFileDescriptor.open(newStateName,
1607 ParcelFileDescriptor.MODE_READ_WRITE |
1608 ParcelFileDescriptor.MODE_CREATE |
1609 ParcelFileDescriptor.MODE_TRUNCATE);
1610
1611 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001612
1613 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001614 //
1615 // !!! TODO: the restored data should be migrated on the server
1616 // side into the current dataset. In that case the new state file
1617 // we just created would reflect the data already extant in the
1618 // backend, so there'd be nothing more to do. Until that happens,
1619 // however, we need to make sure that we record the data to the
1620 // current backend dataset. (Yes, this means shipping the data over
1621 // the wire in both directions. That's bad, but consistency comes
1622 // first, then efficiency.) Once we introduce server-side data
1623 // migration to the newly-restored device's dataset, we will change
1624 // the following from a discard of the newly-written state to the
1625 // "correct" operation of renaming into the canonical state blob.
1626 newStateName.delete(); // TODO: remove; see above comment
1627 //newStateName.renameTo(savedStateName); // TODO: replace with this
1628
Dan Egnorbb9001c2009-07-27 12:20:13 -07001629 int size = (int) backupDataName.length();
1630 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001631 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001632 Log.e(TAG, "Error restoring data for " + packageName, e);
1633 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1634
Christopher Tate96733042009-07-20 14:49:13 -07001635 // If the agent fails restore, it might have put the app's data
1636 // into an incoherent state. For consistency we wipe its data
1637 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001638 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001639 } finally {
1640 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001641 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1642 try { if (newState != null) newState.close(); } catch (IOException e) {}
1643 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001644 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001645 }
1646 }
1647
Christopher Tateee0e78a2009-07-02 11:17:03 -07001648 class PerformClearThread extends Thread {
1649 IBackupTransport mTransport;
1650 PackageInfo mPackage;
1651
1652 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1653 mTransport = transport;
1654 mPackage = packageInfo;
1655 }
1656
1657 @Override
1658 public void run() {
1659 try {
1660 // Clear the on-device backup state to ensure a full backup next time
1661 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1662 File stateFile = new File(stateDir, mPackage.packageName);
1663 stateFile.delete();
1664
1665 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001666 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001667 mTransport.clearBackupData(mPackage);
1668 } catch (RemoteException e) {
1669 // can't happen; the transport is local
1670 } finally {
1671 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001672 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001673 mTransport.finishBackup();
1674 } catch (RemoteException e) {
1675 // can't happen; the transport is local
1676 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001677
1678 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001679 synchronized (mQueueLock) {
1680 mBackupOrRestoreInProgress = false;
1681 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001682 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001683 }
1684 }
1685 }
1686
Christopher Tate4cc86e12009-09-21 19:36:51 -07001687 class PerformInitializeThread extends Thread {
1688 HashSet<String> mQueue;
1689
1690 PerformInitializeThread(HashSet<String> transportNames) {
1691 mQueue = transportNames;
1692 }
1693
1694 @Override
1695 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001696 try {
1697 for (String transportName : mQueue) {
1698 IBackupTransport transport = getTransport(transportName);
1699 if (transport == null) {
1700 Log.e(TAG, "Requested init for " + transportName + " but not found");
1701 continue;
1702 }
1703
Dan Egnor726247c2009-09-29 19:12:31 -07001704 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
1705 EventLog.writeEvent(BACKUP_START_EVENT, transport.transportDirName());
1706 long startRealtime = SystemClock.elapsedRealtime();
1707 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001708
Christopher Tate4cc86e12009-09-21 19:36:51 -07001709 if (status == BackupConstants.TRANSPORT_OK) {
1710 status = transport.finishBackup();
1711 }
1712
1713 // Okay, the wipe really happened. Clean up our local bookkeeping.
1714 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001715 Log.i(TAG, "Device init successful");
1716 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1717 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1718 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
1719 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001720 synchronized (mQueueLock) {
1721 recordInitPendingLocked(false, transportName);
1722 }
Dan Egnor726247c2009-09-29 19:12:31 -07001723 } else {
1724 // If this didn't work, requeue this one and try again
1725 // after a suitable interval
1726 Log.e(TAG, "Transport error in initializeDevice()");
1727 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001728 synchronized (mQueueLock) {
1729 recordInitPendingLocked(true, transportName);
1730 }
1731 // do this via another alarm to make sure of the wakelock states
1732 long delay = transport.requestBackupTime();
1733 if (DEBUG) Log.w(TAG, "init failed on "
1734 + transportName + " resched in " + delay);
1735 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1736 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001737 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001738 }
1739 } catch (RemoteException e) {
1740 // can't happen; the transports are local
1741 } catch (Exception e) {
1742 Log.e(TAG, "Unexpected error performing init", e);
1743 } finally {
1744 // Done; indicate that we're finished and release the wakelock
1745 synchronized (mQueueLock) {
1746 mInitInProgress = false;
1747 }
1748 mWakelock.release();
1749 }
1750 }
1751 }
1752
Christopher Tatedf01dea2009-06-09 20:45:02 -07001753
Christopher Tate487529a2009-04-29 14:03:25 -07001754 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001755
Dan Egnor852f8e42009-09-30 11:20:45 -07001756 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001757 // Record that we need a backup pass for the caller. Since multiple callers
1758 // may share a uid, we need to note all candidates within that uid and schedule
1759 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001760 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001761
Christopher Tate63d27002009-06-16 17:16:42 -07001762 // If the caller does not hold the BACKUP permission, it can only request a
1763 // backup of its own data.
1764 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001765 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001766 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1767 targets = mBackupParticipants.get(Binder.getCallingUid());
1768 } else {
1769 // a caller with full permission can ask to back up any participating app
1770 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001771 targets = new HashSet<ApplicationInfo>();
1772 int N = mBackupParticipants.size();
1773 for (int i = 0; i < N; i++) {
1774 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1775 if (s != null) {
1776 targets.addAll(s);
1777 }
1778 }
1779 }
Christopher Tate487529a2009-04-29 14:03:25 -07001780 if (targets != null) {
1781 synchronized (mQueueLock) {
1782 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001783 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001784 // validate the caller-supplied package name against the known set of
1785 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001786 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001787 // Add the caller to the set of pending backups. If there is
1788 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001789 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001790 if (mPendingBackups.put(app, req) == null) {
1791 // Journal this request in case of crash. The put()
1792 // operation returned null when this package was not already
1793 // in the set; we want to avoid touching the disk redundantly.
1794 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001795
Christopher Tate22b60d82009-07-07 16:36:02 -07001796 if (DEBUG) {
1797 int numKeys = mPendingBackups.size();
1798 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1799 for (BackupRequest b : mPendingBackups.values()) {
1800 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1801 }
1802 }
1803 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001804 }
1805 }
Christopher Tate487529a2009-04-29 14:03:25 -07001806 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001807 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001808 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1809 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001810 }
1811 }
Christopher Tate46758122009-05-06 11:22:00 -07001812
Christopher Tatecde87f42009-06-12 12:55:53 -07001813 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001814 RandomAccessFile out = null;
1815 try {
1816 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1817 out = new RandomAccessFile(mJournal, "rws");
1818 out.seek(out.length());
1819 out.writeUTF(str);
1820 } catch (IOException e) {
1821 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1822 mJournal = null;
1823 } finally {
1824 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001825 }
1826 }
1827
Christopher Tateee0e78a2009-07-02 11:17:03 -07001828 // Clear the given package's backup data from the current transport
1829 public void clearBackupData(String packageName) {
1830 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1831 PackageInfo info;
1832 try {
1833 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1834 } catch (NameNotFoundException e) {
1835 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1836 return;
1837 }
1838
1839 // If the caller does not hold the BACKUP permission, it can only request a
1840 // wipe of its own backed-up data.
1841 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001842 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001843 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1844 apps = mBackupParticipants.get(Binder.getCallingUid());
1845 } else {
1846 // a caller with full permission can ask to back up any participating app
1847 // !!! TODO: allow data-clear of ANY app?
1848 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1849 apps = new HashSet<ApplicationInfo>();
1850 int N = mBackupParticipants.size();
1851 for (int i = 0; i < N; i++) {
1852 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1853 if (s != null) {
1854 apps.addAll(s);
1855 }
1856 }
1857 }
1858
1859 // now find the given package in the set of candidate apps
1860 for (ApplicationInfo app : apps) {
1861 if (app.packageName.equals(packageName)) {
1862 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1863 // found it; fire off the clear request
1864 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001865 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001866 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001867 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1868 new ClearParams(getTransport(mCurrentTransport), info));
1869 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001870 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001871 }
1872 break;
1873 }
1874 }
1875 }
1876
Christopher Tateace7f092009-06-15 18:07:25 -07001877 // Run a backup pass immediately for any applications that have declared
1878 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001879 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001881
Christopher Tateace7f092009-06-15 18:07:25 -07001882 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001883 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001884 // Because the alarms we are using can jitter, and we want an *immediate*
1885 // backup pass to happen, we restart the timer beginning with "next time,"
1886 // then manually fire the backup trigger intent ourselves.
1887 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001888 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001889 mRunBackupIntent.send();
1890 } catch (PendingIntent.CanceledException e) {
1891 // should never happen
1892 Log.e(TAG, "run-backup intent cancelled!");
1893 }
Christopher Tate46758122009-05-06 11:22:00 -07001894 }
1895 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001896
Christopher Tate8031a3d2009-07-06 16:36:05 -07001897 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001898 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1900 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001901
Christopher Tate4cc86e12009-09-21 19:36:51 -07001902 Log.i(TAG, "Backup enabled => " + enable);
1903
Christopher Tate6ef58a12009-06-29 14:56:28 -07001904 boolean wasEnabled = mEnabled;
1905 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001906 Settings.Secure.putInt(mContext.getContentResolver(),
1907 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001908 mEnabled = enable;
1909 }
1910
Christopher Tate49401dd2009-07-01 12:34:29 -07001911 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001912 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001913 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001914 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001915 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001916 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001917 if (DEBUG) Log.i(TAG, "Opting out of backup");
1918
Christopher Tateb6787f22009-07-02 17:40:45 -07001919 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001920
1921 // This also constitutes an opt-out, so we wipe any data for
1922 // this device from the backend. We start that process with
1923 // an alarm in order to guarantee wakelock states.
1924 if (wasEnabled && mProvisioned) {
1925 // NOTE: we currently flush every registered transport, not just
1926 // the currently-active one.
1927 HashSet<String> allTransports;
1928 synchronized (mTransports) {
1929 allTransports = new HashSet<String>(mTransports.keySet());
1930 }
1931 // build the set of transports for which we are posting an init
1932 for (String transport : allTransports) {
1933 recordInitPendingLocked(true, transport);
1934 }
1935 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1936 mRunInitIntent);
1937 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001938 }
1939 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001940 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001941
Christopher Tate8031a3d2009-07-06 16:36:05 -07001942 // Mark the backup service as having been provisioned
1943 public void setBackupProvisioned(boolean available) {
1944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1945 "setBackupProvisioned");
1946
1947 boolean wasProvisioned = mProvisioned;
1948 synchronized (this) {
1949 Settings.Secure.putInt(mContext.getContentResolver(),
1950 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1951 mProvisioned = available;
1952 }
1953
1954 synchronized (mQueueLock) {
1955 if (available && !wasProvisioned && mEnabled) {
1956 // we're now good to go, so start the backup alarms
1957 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1958 } else if (!available) {
1959 // No longer enabled, so stop running backups
1960 Log.w(TAG, "Backup service no longer provisioned");
1961 mAlarmManager.cancel(mRunBackupIntent);
1962 }
1963 }
1964 }
1965
1966 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07001967 // We used to use setInexactRepeating(), but that may be linked to
1968 // backups running at :00 more often than not, creating load spikes.
1969 // Schedule at an exact time for now, and also add a bit of "fuzz".
1970
1971 Random random = new Random();
1972 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
1973 random.nextInt(FUZZ_MILLIS);
1974 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
1975 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001976 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001977 }
1978
Christopher Tate6ef58a12009-06-29 14:56:28 -07001979 // Report whether the backup mechanism is currently enabled
1980 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001982 return mEnabled; // no need to synchronize just to read it
1983 }
1984
Christopher Tate91717492009-06-26 21:07:13 -07001985 // Report the name of the currently active transport
1986 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001988 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001989 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001990 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001991 }
1992
Christopher Tate91717492009-06-26 21:07:13 -07001993 // Report all known, available backup transports
1994 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001996
Christopher Tate91717492009-06-26 21:07:13 -07001997 String[] list = null;
1998 ArrayList<String> known = new ArrayList<String>();
1999 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2000 if (entry.getValue() != null) {
2001 known.add(entry.getKey());
2002 }
2003 }
2004
2005 if (known.size() > 0) {
2006 list = new String[known.size()];
2007 known.toArray(list);
2008 }
2009 return list;
2010 }
2011
2012 // Select which transport to use for the next backup operation. If the given
2013 // name is not one of the available transports, no action is taken and the method
2014 // returns null.
2015 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002017
2018 synchronized (mTransports) {
2019 String prevTransport = null;
2020 if (mTransports.get(transport) != null) {
2021 prevTransport = mCurrentTransport;
2022 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002023 Settings.Secure.putString(mContext.getContentResolver(),
2024 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002025 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2026 + " returning " + prevTransport);
2027 } else {
2028 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2029 }
2030 return prevTransport;
2031 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002032 }
2033
2034 // Callback: a requested backup agent has been instantiated. This should only
2035 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002036 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002037 synchronized(mAgentConnectLock) {
2038 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2039 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2040 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2041 mConnectedAgent = agent;
2042 mConnecting = false;
2043 } else {
2044 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2045 + " claiming agent connected");
2046 }
2047 mAgentConnectLock.notifyAll();
2048 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002049 }
2050
2051 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2052 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002053 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002054 public void agentDisconnected(String packageName) {
2055 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002056 synchronized(mAgentConnectLock) {
2057 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2058 mConnectedAgent = null;
2059 mConnecting = false;
2060 } else {
2061 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2062 + " claiming agent disconnected");
2063 }
2064 mAgentConnectLock.notifyAll();
2065 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002066 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002067
Christopher Tate8c850b72009-06-07 19:33:20 -07002068 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002069 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002071
2072 synchronized(this) {
2073 if (mActiveRestoreSession != null) {
2074 Log.d(TAG, "Restore session requested but one already active");
2075 return null;
2076 }
Christopher Tate91717492009-06-26 21:07:13 -07002077 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002078 }
2079 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002080 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002081
Christopher Tate9b3905c2009-06-08 15:24:01 -07002082 // ----- Restore session -----
2083
2084 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002085 private static final String TAG = "RestoreSession";
2086
Christopher Tate9b3905c2009-06-08 15:24:01 -07002087 private IBackupTransport mRestoreTransport = null;
2088 RestoreSet[] mRestoreSets = null;
2089
Christopher Tate91717492009-06-26 21:07:13 -07002090 RestoreSession(String transport) {
2091 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002092 }
2093
2094 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002095 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002097 "getAvailableRestoreSets");
2098
Christopher Tatef68eb502009-06-16 11:02:01 -07002099 try {
Christopher Tate43383042009-07-13 15:17:13 -07002100 if (mRestoreTransport == null) {
2101 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002102 return null;
2103 }
2104 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002105 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002106 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002107 }
2108 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002109 } catch (Exception e) {
2110 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2111 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002112 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002113 }
2114
Dan Egnor0084da52009-07-29 12:57:16 -07002115 public synchronized int performRestore(long token, IRestoreObserver observer) {
2116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2117 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002118
Christopher Tatef2c321a2009-08-10 15:43:36 -07002119 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2120 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002121
Dan Egnor0084da52009-07-29 12:57:16 -07002122 if (mRestoreTransport == null || mRestoreSets == null) {
2123 Log.e(TAG, "Ignoring performRestore() with no restore set");
2124 return -1;
2125 }
2126
Christopher Tate21ab6a52009-09-24 18:01:46 -07002127 synchronized (mQueueLock) {
2128 if (mBackupOrRestoreInProgress) {
2129 Log.e(TAG, "Backup pass in progress, restore aborted");
2130 return -1;
2131 }
2132
2133 for (int i = 0; i < mRestoreSets.length; i++) {
2134 if (token == mRestoreSets[i].token) {
2135 long oldId = Binder.clearCallingIdentity();
2136 // Suppress backups until the restore operation is finished
2137 mBackupOrRestoreInProgress = true;
2138 mWakelock.acquire();
2139 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2140 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2141 mBackupHandler.sendMessage(msg);
2142 Binder.restoreCallingIdentity(oldId);
2143 return 0;
2144 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002145 }
2146 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002147
2148 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002149 return -1;
2150 }
2151
Dan Egnor0084da52009-07-29 12:57:16 -07002152 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002154 "endRestoreSession");
2155
Dan Egnor0084da52009-07-29 12:57:16 -07002156 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002157
Dan Egnor0084da52009-07-29 12:57:16 -07002158 synchronized (this) {
2159 try {
2160 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2161 } catch (Exception e) {
2162 Log.e(TAG, "Error in finishRestore", e);
2163 } finally {
2164 mRestoreTransport = null;
2165 }
2166 }
2167
2168 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002169 if (BackupManagerService.this.mActiveRestoreSession == this) {
2170 BackupManagerService.this.mActiveRestoreSession = null;
2171 } else {
2172 Log.e(TAG, "ending non-current restore session");
2173 }
2174 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002175 }
2176 }
2177
Christopher Tate043dadc2009-06-02 16:11:00 -07002178
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002179 @Override
2180 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2181 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002182 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002183 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2184 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2185 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2186 + (!mInitInProgress ? "not " : "") + "initializing");
2187 pw.println("Last backup pass: " + mLastBackupPass
2188 + " (now = " + System.currentTimeMillis() + ')');
2189 pw.println(" next scheduled: " + mNextBackupPass);
2190
Christopher Tate91717492009-06-26 21:07:13 -07002191 pw.println("Available transports:");
2192 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002193 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2194 try {
2195 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2196 for (File f : dir.listFiles()) {
2197 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2198 }
2199 } catch (RemoteException e) {
2200 Log.e(TAG, "Error in transportDirName()", e);
2201 pw.println(" Error: " + e);
2202 }
Christopher Tate91717492009-06-26 21:07:13 -07002203 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002204
2205 pw.println("Pending init: " + mPendingInits.size());
2206 for (String s : mPendingInits) {
2207 pw.println(" " + s);
2208 }
2209
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002210 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002211 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002212 for (int i=0; i<N; i++) {
2213 int uid = mBackupParticipants.keyAt(i);
2214 pw.print(" uid: ");
2215 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002216 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2217 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002218 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002219 }
2220 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002221
Christopher Tate73e02522009-07-15 14:18:26 -07002222 pw.println("Ever backed up: " + mEverStoredApps.size());
2223 for (String pkg : mEverStoredApps) {
2224 pw.println(" " + pkg);
2225 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002226
2227 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002228 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002229 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002230 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002231 }
2232 }
Christopher Tate487529a2009-04-29 14:03:25 -07002233}