blob: 82a7c1c6d90ec30c5bbcd1e72d45e6b16f77f019 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070049import android.os.SystemClock;
50import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.util.Log;
52import android.util.SparseArray;
53
54import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070055import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070056import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070057import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070058
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070060import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tate6785dd82009-06-18 15:58:25 -070063import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070082 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Christopher Tate8031a3d2009-07-06 16:36:05 -070088 // The amount of time between the initial provisioning of the device and
89 // the first backup pass.
90 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
91
Christopher Tate4cc86e12009-09-21 19:36:51 -070092 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
93 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
94 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070095 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070096 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070097 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070098 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -070099 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700100
Dan Egnorbb9001c2009-07-27 12:20:13 -0700101 // Event tags -- see system/core/logcat/event-log-tags
102 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
103 private static final int BACKUP_START_EVENT = 2821;
104 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
105 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
106 private static final int BACKUP_PACKAGE_EVENT = 2824;
107 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700108 private static final int BACKUP_RESET_EVENT = 2826;
Dan Egnor726247c2009-09-29 19:12:31 -0700109 private static final int BACKUP_INITIALIZE_EVENT = 2827;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700110
111 private static final int RESTORE_START_EVENT = 2830;
112 private static final int RESTORE_TRANSPORT_FAILURE_EVENT = 2831;
113 private static final int RESTORE_AGENT_FAILURE_EVENT = 2832;
114 private static final int RESTORE_PACKAGE_EVENT = 2833;
115 private static final int RESTORE_SUCCESS_EVENT = 2834;
116
Christopher Tatec7b31e32009-06-10 15:49:30 -0700117 // Timeout interval for deciding that a bind or clear-data has taken too long
118 static final long TIMEOUT_INTERVAL = 10 * 1000;
119
Christopher Tate487529a2009-04-29 14:03:25 -0700120 private Context mContext;
121 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700122 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700123 private PowerManager mPowerManager;
124 private AlarmManager mAlarmManager;
125
Christopher Tate73e02522009-07-15 14:18:26 -0700126 boolean mEnabled; // access to this is synchronized on 'this'
127 boolean mProvisioned;
128 PowerManager.WakeLock mWakelock;
129 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700130 PendingIntent mRunBackupIntent, mRunInitIntent;
131 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700132 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700133 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700134 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700135 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700136 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700137 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700138 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700139
Christopher Tate181fafa2009-05-14 11:12:14 -0700140 BackupRequest(ApplicationInfo app, boolean isFull) {
141 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700142 fullBackup = isFull;
143 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700144
145 public String toString() {
146 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
147 }
Christopher Tate46758122009-05-06 11:22:00 -0700148 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400149 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700150 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700151 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700152
153 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700154 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700155
156 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700157 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700158
Christopher Tate043dadc2009-06-02 16:11:00 -0700159 // The thread performing the sequence of queued backups binds to each app's agent
160 // in succession. Bind notifications are asynchronously delivered through the
161 // Activity Manager; use this lock object to signal when a requested binding has
162 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700163 final Object mAgentConnectLock = new Object();
164 IBackupAgent mConnectedAgent;
165 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700166 volatile boolean mBackupOrRestoreInProgress = false;
Christopher Tate55f931a2009-09-29 17:17:34 -0700167 volatile long mLastBackupPass;
168 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700169
Christopher Tate55f931a2009-09-29 17:17:34 -0700170 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700171 final Object mClearDataLock = new Object();
172 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700173
Christopher Tate91717492009-06-26 21:07:13 -0700174 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700175 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700176 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700177 String mCurrentTransport;
178 IBackupTransport mLocalTransport, mGoogleTransport;
179 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700180
Christopher Tate73e02522009-07-15 14:18:26 -0700181 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700182 public IBackupTransport transport;
183 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700184 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700185
Dan Egnor156411d2009-06-26 13:20:02 -0700186 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700187 transport = _transport;
188 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700189 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700190 }
191 }
192
Christopher Tate73e02522009-07-15 14:18:26 -0700193 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700194 public IBackupTransport transport;
195 public PackageInfo packageInfo;
196
197 ClearParams(IBackupTransport _transport, PackageInfo _info) {
198 transport = _transport;
199 packageInfo = _info;
200 }
201 }
202
Christopher Tate5cb400b2009-06-25 16:03:14 -0700203 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700204 File mBaseStateDir;
205 File mDataDir;
206 File mJournalDir;
207 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700208
209 // Keep a log of all the apps we've ever backed up
210 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700211 HashSet<String> mEverStoredApps = new HashSet<String>();
212
Christopher Tate4cc86e12009-09-21 19:36:51 -0700213 // Persistently track the need to do a full init
214 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
215 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700216 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700217
Christopher Tate487529a2009-04-29 14:03:25 -0700218 public BackupManagerService(Context context) {
219 mContext = context;
220 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700221 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700222
Christopher Tateb6787f22009-07-02 17:40:45 -0700223 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
224 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
225
Christopher Tate22b87872009-05-04 16:41:53 -0700226 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700227 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700228 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700229 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700230 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700231 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700232 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700233
Christopher Tate4cc86e12009-09-21 19:36:51 -0700234 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700235 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700236 IntentFilter filter = new IntentFilter();
237 filter.addAction(RUN_BACKUP_ACTION);
238 context.registerReceiver(mRunBackupReceiver, filter,
239 android.Manifest.permission.BACKUP, null);
240
241 mRunInitReceiver = new RunInitializeReceiver();
242 filter = new IntentFilter();
243 filter.addAction(RUN_INITIALIZE_ACTION);
244 context.registerReceiver(mRunInitReceiver, filter,
245 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700246
247 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700248 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
249 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
250
Christopher Tate4cc86e12009-09-21 19:36:51 -0700251 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
252 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
253 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
254
Christopher Tatecde87f42009-06-12 12:55:53 -0700255 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700256 mJournalDir = new File(mBaseStateDir, "pending");
257 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700258 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700259
Christopher Tate73e02522009-07-15 14:18:26 -0700260 // Set up the various sorts of package tracking we do
261 initPackageTracking();
262
Christopher Tateabce4e82009-06-18 18:35:32 -0700263 // Build our mapping of uid to backup client services. This implicitly
264 // schedules a backup pass on the Package Manager metadata the first
265 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700266 synchronized (mBackupParticipants) {
267 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700268 }
269
Dan Egnor87a02bc2009-06-17 02:30:10 -0700270 // Set up our transport options and initialize the default transport
271 // TODO: Have transports register themselves somehow?
272 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700273 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700274 ComponentName localName = new ComponentName(context, LocalTransport.class);
275 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700276
Christopher Tate91717492009-06-26 21:07:13 -0700277 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700278 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
279 Settings.Secure.BACKUP_TRANSPORT);
280 if ("".equals(mCurrentTransport)) {
281 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700282 }
Christopher Tate91717492009-06-26 21:07:13 -0700283 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
284
285 // Attach to the Google backup transport. When this comes up, it will set
286 // itself as the current transport because we explicitly reset mCurrentTransport
287 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700288 Intent intent = new Intent().setComponent(new ComponentName(
289 "com.google.android.backup",
290 "com.google.android.backup.BackupTransportService"));
291 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700292
Christopher Tatecde87f42009-06-12 12:55:53 -0700293 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700294 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700295 parseLeftoverJournals();
296
Christopher Tateb6787f22009-07-02 17:40:45 -0700297 // Power management
298 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
299
300 // Start the backup passes going
301 setBackupEnabled(areEnabled);
302 }
303
304 private class RunBackupReceiver extends BroadcastReceiver {
305 public void onReceive(Context context, Intent intent) {
306 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700307 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700308 if (mPendingInits.size() > 0) {
309 // If there are pending init operations, we process those
310 // and then settle into the usual periodic backup schedule.
311 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
312 try {
313 mAlarmManager.cancel(mRunInitIntent);
314 mRunInitIntent.send();
315 } catch (PendingIntent.CanceledException ce) {
316 Log.e(TAG, "Run init intent cancelled");
317 // can't really do more than bail here
318 }
319 } else {
320 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700321 // fully set up, in the middle of a backup already,
322 // or racing with an initialize pass.
323 if (mEnabled && mProvisioned
324 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700325 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700326 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700327
328 // Acquire the wakelock and pass it to the backup thread. it will
329 // be released once backup concludes.
330 mWakelock.acquire();
331
332 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
333 mBackupHandler.sendMessage(msg);
334 } else {
335 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700336 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700337 }
338 }
339 }
340 }
341 }
342 }
343
344 private class RunInitializeReceiver extends BroadcastReceiver {
345 public void onReceive(Context context, Intent intent) {
346 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
347 synchronized (mQueueLock) {
348 if (DEBUG) Log.v(TAG, "Running a device init");
349 mInitInProgress = true;
350
351 // Acquire the wakelock and pass it to the init thread. it will
352 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700353 mWakelock.acquire();
354
Christopher Tate4cc86e12009-09-21 19:36:51 -0700355 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700356 mBackupHandler.sendMessage(msg);
357 }
358 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700359 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700360 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700361
Christopher Tate73e02522009-07-15 14:18:26 -0700362 private void initPackageTracking() {
363 if (DEBUG) Log.v(TAG, "Initializing package tracking");
364
Christopher Tatee97e8072009-07-15 16:45:50 -0700365 // Keep a log of what apps we've ever backed up. Because we might have
366 // rebooted in the middle of an operation that was removing something from
367 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700368 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700369 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700370
Christopher Tatee97e8072009-07-15 16:45:50 -0700371 // If we were in the middle of removing something from the ever-backed-up
372 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700373 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700374 if (tempProcessedFile.exists()) {
375 tempProcessedFile.delete();
376 }
377
Dan Egnor852f8e42009-09-30 11:20:45 -0700378 // If there are previous contents, parse them out then start a new
379 // file to continue the recordkeeping.
380 if (mEverStored.exists()) {
381 RandomAccessFile temp = null;
382 RandomAccessFile in = null;
383
384 try {
385 temp = new RandomAccessFile(tempProcessedFile, "rws");
386 in = new RandomAccessFile(mEverStored, "r");
387
388 while (true) {
389 PackageInfo info;
390 String pkg = in.readUTF();
391 try {
392 info = mPackageManager.getPackageInfo(pkg, 0);
393 mEverStoredApps.add(pkg);
394 temp.writeUTF(pkg);
395 if (DEBUG) Log.v(TAG, " + " + pkg);
396 } catch (NameNotFoundException e) {
397 // nope, this package was uninstalled; don't include it
398 if (DEBUG) Log.v(TAG, " - " + pkg);
399 }
400 }
401 } catch (EOFException e) {
402 // Once we've rewritten the backup history log, atomically replace the
403 // old one with the new one then reopen the file for continuing use.
404 if (!tempProcessedFile.renameTo(mEverStored)) {
405 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
406 }
407 } catch (IOException e) {
408 Log.e(TAG, "Error in processed file", e);
409 } finally {
410 try { if (temp != null) temp.close(); } catch (IOException e) {}
411 try { if (in != null) in.close(); } catch (IOException e) {}
412 }
413 }
414
Christopher Tate73e02522009-07-15 14:18:26 -0700415 // Register for broadcasts about package install, etc., so we can
416 // update the provider list.
417 IntentFilter filter = new IntentFilter();
418 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
419 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
420 filter.addDataScheme("package");
421 mContext.registerReceiver(mBroadcastReceiver, filter);
422 }
423
Christopher Tatecde87f42009-06-12 12:55:53 -0700424 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700425 for (File f : mJournalDir.listFiles()) {
426 if (mJournal == null || f.compareTo(mJournal) != 0) {
427 // This isn't the current journal, so it must be a leftover. Read
428 // out the package names mentioned there and schedule them for
429 // backup.
430 RandomAccessFile in = null;
431 try {
432 Log.i(TAG, "Found stale backup journal, scheduling:");
433 in = new RandomAccessFile(f, "r");
434 while (true) {
435 String packageName = in.readUTF();
436 Log.i(TAG, " + " + packageName);
437 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700438 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700439 } catch (EOFException e) {
440 // no more data; we're done
441 } catch (Exception e) {
442 Log.e(TAG, "Can't read " + f, e);
443 } finally {
444 // close/delete the file
445 try { if (in != null) in.close(); } catch (IOException e) {}
446 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700447 }
448 }
449 }
450 }
451
Christopher Tate4cc86e12009-09-21 19:36:51 -0700452 // Maintain persistent state around whether need to do an initialize operation.
453 // Must be called with the queue lock held.
454 void recordInitPendingLocked(boolean isPending, String transportName) {
455 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
456 + " on transport " + transportName);
457 try {
458 IBackupTransport transport = getTransport(transportName);
459 String transportDirName = transport.transportDirName();
460 File stateDir = new File(mBaseStateDir, transportDirName);
461 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
462
463 if (isPending) {
464 // We need an init before we can proceed with sending backup data.
465 // Record that with an entry in our set of pending inits, as well as
466 // journaling it via creation of a sentinel file.
467 mPendingInits.add(transportName);
468 try {
469 (new FileOutputStream(initPendingFile)).close();
470 } catch (IOException ioe) {
471 // Something is badly wrong with our permissions; just try to move on
472 }
473 } else {
474 // No more initialization needed; wipe the journal and reset our state.
475 initPendingFile.delete();
476 mPendingInits.remove(transportName);
477 }
478 } catch (RemoteException e) {
479 // can't happen; the transport is local
480 }
481 }
482
Christopher Tated55e18a2009-09-21 10:12:59 -0700483 // Reset all of our bookkeeping, in response to having been told that
484 // the backend data has been wiped [due to idle expiry, for example],
485 // so we must re-upload all saved settings.
486 void resetBackupState(File stateFileDir) {
487 synchronized (mQueueLock) {
488 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700489 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700490 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700491
492 // Remove all the state files
493 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700494 // ... but don't touch the needs-init sentinel
495 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
496 sf.delete();
497 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700498 }
499
500 // Enqueue a new backup of every participant
501 int N = mBackupParticipants.size();
502 for (int i=0; i<N; i++) {
503 int uid = mBackupParticipants.keyAt(i);
504 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
505 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700506 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700507 }
508 }
509 }
510 }
511
Christopher Tate91717492009-06-26 21:07:13 -0700512 // Add a transport to our set of available backends
513 private void registerTransport(String name, IBackupTransport transport) {
514 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700515 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700516 mTransports.put(name, transport);
517 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700518
519 // If the init sentinel file exists, we need to be sure to perform the init
520 // as soon as practical. We also create the state directory at registration
521 // time to ensure it's present from the outset.
522 try {
523 String transportName = transport.transportDirName();
524 File stateDir = new File(mBaseStateDir, transportName);
525 stateDir.mkdirs();
526
527 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
528 if (initSentinel.exists()) {
529 synchronized (mQueueLock) {
530 mPendingInits.add(transportName);
531
532 // TODO: pick a better starting time than now + 1 minute
533 long delay = 1000 * 60; // one minute, in milliseconds
534 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
535 System.currentTimeMillis() + delay, mRunInitIntent);
536 }
537 }
538 } catch (RemoteException e) {
539 // can't happen, the transport is local
540 }
Christopher Tate91717492009-06-26 21:07:13 -0700541 }
542
Christopher Tate3799bc22009-05-06 16:13:56 -0700543 // ----- Track installation/removal of packages -----
544 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
545 public void onReceive(Context context, Intent intent) {
546 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
547
548 Uri uri = intent.getData();
549 if (uri == null) {
550 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700551 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700552 String pkgName = uri.getSchemeSpecificPart();
553 if (pkgName == null) {
554 return;
555 }
556
557 String action = intent.getAction();
558 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
559 synchronized (mBackupParticipants) {
560 Bundle extras = intent.getExtras();
561 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
562 // The package was just upgraded
563 updatePackageParticipantsLocked(pkgName);
564 } else {
565 // The package was just added
566 addPackageParticipantsLocked(pkgName);
567 }
568 }
569 }
570 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
571 Bundle extras = intent.getExtras();
572 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
573 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
574 } else {
575 synchronized (mBackupParticipants) {
576 removePackageParticipantsLocked(pkgName);
577 }
578 }
579 }
580 }
581 };
582
Dan Egnor87a02bc2009-06-17 02:30:10 -0700583 // ----- Track connection to GoogleBackupTransport service -----
584 ServiceConnection mGoogleConnection = new ServiceConnection() {
585 public void onServiceConnected(ComponentName name, IBinder service) {
586 if (DEBUG) Log.v(TAG, "Connected to Google transport");
587 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700588 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700589 }
590
591 public void onServiceDisconnected(ComponentName name) {
592 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
593 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700594 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700595 }
596 };
597
Joe Onorato8ad02812009-05-13 01:41:44 -0400598 // ----- Run the actual backup process asynchronously -----
599
Christopher Tate181fafa2009-05-14 11:12:14 -0700600 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400601 public void handleMessage(Message msg) {
602
603 switch (msg.what) {
604 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700605 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700606 mLastBackupPass = System.currentTimeMillis();
607 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
608
Christopher Tate91717492009-06-26 21:07:13 -0700609 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700610 if (transport == null) {
611 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700612 synchronized (mQueueLock) {
613 mBackupOrRestoreInProgress = false;
614 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700615 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700616 break;
617 }
618
Joe Onorato8ad02812009-05-13 01:41:44 -0400619 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700620 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400621 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700622 // Do we have any work to do?
623 if (mPendingBackups.size() > 0) {
624 for (BackupRequest b: mPendingBackups.values()) {
625 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700626 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700627 Log.v(TAG, "clearing pending backups");
628 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700629
Christopher Tate49401dd2009-07-01 12:34:29 -0700630 // Start a new backup-queue journal file too
Dan Egnor852f8e42009-09-30 11:20:45 -0700631 File oldJournal = mJournal;
632 mJournal = null;
Christopher Tate49401dd2009-07-01 12:34:29 -0700633
634 // At this point, we have started a new journal file, and the old
635 // file identity is being passed to the backup processing thread.
636 // When it completes successfully, that old journal file will be
637 // deleted. If we crash prior to that, the old journal is parsed
638 // at next boot and the journaled requests fulfilled.
639 (new PerformBackupThread(transport, queue, oldJournal)).start();
640 } else {
641 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700642 synchronized (mQueueLock) {
643 mBackupOrRestoreInProgress = false;
644 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700645 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700646 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400647 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700648 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700649 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700650
651 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400652 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700653
654 case MSG_RUN_RESTORE:
655 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700656 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400657 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700658 (new PerformRestoreThread(params.transport, params.observer,
659 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700660 break;
661 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700662
663 case MSG_RUN_CLEAR:
664 {
665 ClearParams params = (ClearParams)msg.obj;
666 (new PerformClearThread(params.transport, params.packageInfo)).start();
667 break;
668 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700669
670 case MSG_RUN_INITIALIZE:
671 {
672 HashSet<String> queue;
673
674 // Snapshot the pending-init queue and work on that
675 synchronized (mQueueLock) {
676 queue = new HashSet<String>(mPendingInits);
677 mPendingInits.clear();
678 }
679
680 (new PerformInitializeThread(queue)).start();
681 break;
682 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400683 }
684 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400685 }
686
Christopher Tate181fafa2009-05-14 11:12:14 -0700687 // Add the backup agents in the given package to our set of known backup participants.
688 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700689 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700690 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700691 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700692 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700693 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700694 }
695
Christopher Tate181fafa2009-05-14 11:12:14 -0700696 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700697 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700698 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700699 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
700 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700701 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700702 + " uid=" + p.applicationInfo.uid
703 + " killAfterRestore="
704 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
705 + " restoreNeedsApplication="
706 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
707 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700708 }
709 }
710
Dan Egnorefe52642009-06-24 00:16:33 -0700711 for (PackageInfo pkg : targetPkgs) {
712 if (packageName == null || pkg.packageName.equals(packageName)) {
713 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700714 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700715 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700716 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700717 mBackupParticipants.put(uid, set);
718 }
Dan Egnorefe52642009-06-24 00:16:33 -0700719 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700720
721 // If we've never seen this app before, schedule a backup for it
722 if (!mEverStoredApps.contains(pkg.packageName)) {
723 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
724 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700725 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700726 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700727 }
Christopher Tate487529a2009-04-29 14:03:25 -0700728 }
729 }
730
Christopher Tate6785dd82009-06-18 15:58:25 -0700731 // Remove the given package's entry from our known active set. If
732 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700733 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700734 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700735 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700736 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700737 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700738 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700739 int flags = PackageManager.GET_SIGNATURES;
740 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700741 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700742 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700743 }
744 } else {
745 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700746 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700747 }
748 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700749 }
750
Joe Onorato8ad02812009-05-13 01:41:44 -0400751 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700752 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700753 if (DEBUG) {
754 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
755 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700756 for (PackageInfo p : agents) {
757 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700758 }
759 }
Dan Egnorefe52642009-06-24 00:16:33 -0700760 for (PackageInfo pkg : agents) {
761 if (packageName == null || pkg.packageName.equals(packageName)) {
762 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700763 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700764 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700765 // Find the existing entry with the same package name, and remove it.
766 // We can't just remove(app) because the instances are different.
767 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700768 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700769 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700770 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700771 break;
772 }
773 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700774 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700775 mBackupParticipants.delete(uid);
776 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700777 }
778 }
779 }
780 }
781
Christopher Tate181fafa2009-05-14 11:12:14 -0700782 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700783 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700784 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700785 int flags = PackageManager.GET_SIGNATURES;
786 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
787 int N = packages.size();
788 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700789 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700790 try {
791 ApplicationInfo app = pkg.applicationInfo;
792 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
793 || app.backupAgentName == null
794 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
795 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
796 packages.remove(a);
797 }
798 else {
799 // we will need the shared library path, so look that up and store it here
800 app = mPackageManager.getApplicationInfo(pkg.packageName,
801 PackageManager.GET_SHARED_LIBRARY_FILES);
802 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
803 }
804 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700805 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700806 }
807 }
Dan Egnorefe52642009-06-24 00:16:33 -0700808 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700809 }
Christopher Tateaa088442009-06-16 18:25:46 -0700810
Christopher Tate3799bc22009-05-06 16:13:56 -0700811 // Reset the given package's known backup participants. Unlike add/remove, the update
812 // action cannot be passed a null package name.
813 void updatePackageParticipantsLocked(String packageName) {
814 if (packageName == null) {
815 Log.e(TAG, "updatePackageParticipants called with null package name");
816 return;
817 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700818 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700819
820 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700821 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700822 removePackageParticipantsLockedInner(packageName, allApps);
823 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700824 }
825
Christopher Tate73e02522009-07-15 14:18:26 -0700826 // Called from the backup thread: record that the given app has been successfully
827 // backed up at least once
828 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700829 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
830
831 synchronized (mEverStoredApps) {
832 if (!mEverStoredApps.add(packageName)) return;
833
834 RandomAccessFile out = null;
835 try {
836 out = new RandomAccessFile(mEverStored, "rws");
837 out.seek(out.length());
838 out.writeUTF(packageName);
839 } catch (IOException e) {
840 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
841 } finally {
842 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700843 }
844 }
845 }
846
Christopher Tatee97e8072009-07-15 16:45:50 -0700847 // Remove our awareness of having ever backed up the given package
848 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700849 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700850
Dan Egnor852f8e42009-09-30 11:20:45 -0700851 synchronized (mEverStoredApps) {
852 // Rewrite the file and rename to overwrite. If we reboot in the middle,
853 // we'll recognize on initialization time that the package no longer
854 // exists and fix it up then.
855 File tempKnownFile = new File(mBaseStateDir, "processed.new");
856 RandomAccessFile known = null;
857 try {
858 known = new RandomAccessFile(tempKnownFile, "rws");
859 mEverStoredApps.remove(packageName);
860 for (String s : mEverStoredApps) {
861 known.writeUTF(s);
862 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700863 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700864 known.close();
865 known = null;
866 if (!tempKnownFile.renameTo(mEverStored)) {
867 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
868 }
869 } catch (IOException e) {
870 // Bad: we couldn't create the new copy. For safety's sake we
871 // abandon the whole process and remove all what's-backed-up
872 // state entirely, meaning we'll force a backup pass for every
873 // participant on the next boot or [re]install.
874 Log.w(TAG, "Error rewriting " + mEverStored, e);
875 mEverStoredApps.clear();
876 tempKnownFile.delete();
877 mEverStored.delete();
878 } finally {
879 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700880 }
881 }
882 }
883
Dan Egnor87a02bc2009-06-17 02:30:10 -0700884 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700885 private IBackupTransport getTransport(String transportName) {
886 synchronized (mTransports) {
887 IBackupTransport transport = mTransports.get(transportName);
888 if (transport == null) {
889 Log.w(TAG, "Requested unavailable transport: " + transportName);
890 }
891 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700892 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700893 }
894
Christopher Tatedf01dea2009-06-09 20:45:02 -0700895 // fire off a backup agent, blocking until it attaches or times out
896 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
897 IBackupAgent agent = null;
898 synchronized(mAgentConnectLock) {
899 mConnecting = true;
900 mConnectedAgent = null;
901 try {
902 if (mActivityManager.bindBackupAgent(app, mode)) {
903 Log.d(TAG, "awaiting agent for " + app);
904
905 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700906 // only wait 10 seconds for the clear data to happen
907 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
908 while (mConnecting && mConnectedAgent == null
909 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700910 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700911 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700912 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700913 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700914 return null;
915 }
916 }
917
918 // if we timed out with no connect, abort and move on
919 if (mConnecting == true) {
920 Log.w(TAG, "Timeout waiting for agent " + app);
921 return null;
922 }
923 agent = mConnectedAgent;
924 }
925 } catch (RemoteException e) {
926 // can't happen
927 }
928 }
929 return agent;
930 }
931
Christopher Tatec7b31e32009-06-10 15:49:30 -0700932 // clear an application's data, blocking until the operation completes or times out
933 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700934 // Don't wipe packages marked allowClearUserData=false
935 try {
936 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
937 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
938 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
939 + packageName);
940 return;
941 }
942 } catch (NameNotFoundException e) {
943 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
944 return;
945 }
946
Christopher Tatec7b31e32009-06-10 15:49:30 -0700947 ClearDataObserver observer = new ClearDataObserver();
948
949 synchronized(mClearDataLock) {
950 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700951 /* This is causing some critical processes to be killed during setup.
952 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700953 try {
954 mActivityManager.clearApplicationUserData(packageName, observer);
955 } catch (RemoteException e) {
956 // can't happen because the activity manager is in this process
957 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700958 */
959 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700960
961 // only wait 10 seconds for the clear data to happen
962 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
963 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
964 try {
965 mClearDataLock.wait(5000);
966 } catch (InterruptedException e) {
967 // won't happen, but still.
968 mClearingData = false;
969 }
970 }
971 }
972 }
973
974 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -0700975 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700976 synchronized(mClearDataLock) {
977 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700978 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700979 }
980 }
981 }
982
Christopher Tate043dadc2009-06-02 16:11:00 -0700983 // ----- Back up a set of applications via a worker thread -----
984
985 class PerformBackupThread extends Thread {
986 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700987 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700988 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700989 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700990 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700991
Christopher Tateaa088442009-06-16 18:25:46 -0700992 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700993 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700994 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700995 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700996 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700997
998 try {
999 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1000 } catch (RemoteException e) {
1001 // can't happen; the transport is local
1002 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001003 }
1004
1005 @Override
1006 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001007 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001008 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001009 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1010
Christopher Tate79588342009-06-30 16:11:49 -07001011 // Backups run at background priority
1012 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1013
Christopher Tate043dadc2009-06-02 16:11:00 -07001014 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001015 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001016
Dan Egnor852f8e42009-09-30 11:20:45 -07001017 // If we haven't stored package manager metadata yet, we must init the transport.
1018 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1019 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1020 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1021 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001022 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001023 if (status == BackupConstants.TRANSPORT_OK) {
1024 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1025 } else {
1026 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
1027 Log.e(TAG, "Transport error in initializeDevice()");
1028 }
Dan Egnor01445162009-09-21 17:04:05 -07001029 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001030
1031 // The package manager doesn't have a proper <application> etc, but since
1032 // it's running here in the system process we can just set up its agent
1033 // directly and use a synthetic BackupRequest. We always run this pass
1034 // because it's cheap and this way we guarantee that we don't get out of
1035 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001036 if (status == BackupConstants.TRANSPORT_OK) {
1037 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1038 mPackageManager, allAgentPackages());
1039 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1040 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1041 status = processOneBackup(pmRequest,
1042 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1043 }
Christopher Tate90967f42009-09-20 15:28:33 -07001044
Dan Egnor01445162009-09-21 17:04:05 -07001045 if (status == BackupConstants.TRANSPORT_OK) {
1046 // Now run all the backups in our queue
1047 status = doQueuedBackups(mTransport);
1048 }
1049
1050 if (status == BackupConstants.TRANSPORT_OK) {
1051 // Tell the transport to finish everything it has buffered
1052 status = mTransport.finishBackup();
1053 if (status == BackupConstants.TRANSPORT_OK) {
1054 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1055 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1056 } else {
Dan Egnor726247c2009-09-29 19:12:31 -07001057 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001058 Log.e(TAG, "Transport error in finishBackup()");
1059 }
1060 }
1061
Dan Egnor01445162009-09-21 17:04:05 -07001062 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001063 // The backend reports that our dataset has been wiped. We need to
1064 // reset all of our bookkeeping and instead run a new backup pass for
Dan Egnor852f8e42009-09-30 11:20:45 -07001065 // everything. This must come after mBackupOrRestoreInProgress is cleared.
Christopher Tated55e18a2009-09-21 10:12:59 -07001066 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1067 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001068 }
1069 } catch (Exception e) {
1070 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001071 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001072 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001073 // If things went wrong, we need to re-stage the apps we had expected
1074 // to be backing up in this pass. This journals the package names in
1075 // the current active pending-backup file, not in the we are holding
1076 // here in mJournal.
1077 if (status != BackupConstants.TRANSPORT_OK) {
1078 Log.w(TAG, "Backup pass unsuccessful, restaging");
1079 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001080 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001081 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001082
1083 // We also want to reset the backup schedule based on whatever
1084 // the transport suggests by way of retry/backoff time.
1085 try {
1086 startBackupAlarmsLocked(mTransport.requestBackupTime());
1087 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001088 }
1089
1090 // Either backup was successful, in which case we of course do not need
1091 // this pass's journal any more; or it failed, in which case we just
1092 // re-enqueued all of these packages in the current active journal.
1093 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001094 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001095 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1096 }
1097
Christopher Tate21ab6a52009-09-24 18:01:46 -07001098 // Only once we're entirely finished do we indicate our completion
1099 // and release the wakelock
1100 synchronized (mQueueLock) {
1101 mBackupOrRestoreInProgress = false;
1102 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001103
1104 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1105 // This must come after mBackupOrRestoreInProgress is cleared.
1106 backupNow();
1107 }
1108
Dan Egnorbb9001c2009-07-27 12:20:13 -07001109 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001110 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001111 }
1112
Dan Egnor01445162009-09-21 17:04:05 -07001113 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001114 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001115 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001116
Christopher Tate0749dcd2009-08-13 15:13:03 -07001117 // Don't run backup, even if requested, if the target app does not have
1118 // the requisite permission
1119 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1120 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1121 Log.w(TAG, "Skipping backup of unprivileged package "
1122 + request.appInfo.packageName);
1123 continue;
1124 }
1125
Christopher Tate043dadc2009-06-02 16:11:00 -07001126 IBackupAgent agent = null;
1127 int mode = (request.fullBackup)
1128 ? IApplicationThread.BACKUP_MODE_FULL
1129 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1130 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001131 agent = bindToAgentSynchronous(request.appInfo, mode);
1132 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001133 int result = processOneBackup(request, agent, transport);
1134 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001135 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001136 } catch (SecurityException ex) {
1137 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001138 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001139 } finally {
1140 try { // unbind even on timeout, just in case
1141 mActivityManager.unbindBackupAgent(request.appInfo);
1142 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001143 }
1144 }
Dan Egnor01445162009-09-21 17:04:05 -07001145
1146 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001147 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001148
Dan Egnor01445162009-09-21 17:04:05 -07001149 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1150 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001151 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001152 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001153
Dan Egnorbb9001c2009-07-27 12:20:13 -07001154 File savedStateName = new File(mStateDir, packageName);
1155 File backupDataName = new File(mDataDir, packageName + ".data");
1156 File newStateName = new File(mStateDir, packageName + ".new");
1157
1158 ParcelFileDescriptor savedState = null;
1159 ParcelFileDescriptor backupData = null;
1160 ParcelFileDescriptor newState = null;
1161
1162 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001163 try {
1164 // Look up the package info & signatures. This is first so that if it
1165 // throws an exception, there's no file setup yet that would need to
1166 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001167 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1168 // The metadata 'package' is synthetic
1169 packInfo = new PackageInfo();
1170 packInfo.packageName = packageName;
1171 } else {
1172 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001173 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001174 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001175
Christopher Tatec7b31e32009-06-10 15:49:30 -07001176 // In a full backup, we pass a null ParcelFileDescriptor as
1177 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001178 if (!request.fullBackup) {
1179 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001180 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001181 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1182 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001183
Dan Egnorbb9001c2009-07-27 12:20:13 -07001184 backupData = ParcelFileDescriptor.open(backupDataName,
1185 ParcelFileDescriptor.MODE_READ_WRITE |
1186 ParcelFileDescriptor.MODE_CREATE |
1187 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001188
Dan Egnorbb9001c2009-07-27 12:20:13 -07001189 newState = ParcelFileDescriptor.open(newStateName,
1190 ParcelFileDescriptor.MODE_READ_WRITE |
1191 ParcelFileDescriptor.MODE_CREATE |
1192 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001193
1194 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001195 agent.doBackup(savedState, backupData, newState);
1196 logBackupComplete(packageName);
1197 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001198 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001199 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001200 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1201 backupDataName.delete();
1202 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001203 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001204 } finally {
1205 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1206 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1207 try { if (newState != null) newState.close(); } catch (IOException e) {}
1208 savedState = backupData = newState = null;
1209 }
1210
1211 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001212 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001213 try {
1214 int size = (int) backupDataName.length();
1215 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001216 if (result == BackupConstants.TRANSPORT_OK) {
1217 backupData = ParcelFileDescriptor.open(backupDataName,
1218 ParcelFileDescriptor.MODE_READ_ONLY);
1219 result = transport.performBackup(packInfo, backupData);
1220 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001221
Dan Egnor83861e72009-09-17 16:17:55 -07001222 // TODO - We call finishBackup() for each application backed up, because
1223 // we need to know now whether it succeeded or failed. Instead, we should
1224 // hold off on finishBackup() until the end, which implies holding off on
1225 // renaming *all* the output state files (see below) until that happens.
1226
Dan Egnor01445162009-09-21 17:04:05 -07001227 if (result == BackupConstants.TRANSPORT_OK) {
1228 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001229 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001230 } else {
1231 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1232 }
1233
1234 // After successful transport, delete the now-stale data
1235 // and juggle the files so that next time we supply the agent
1236 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001237 if (result == BackupConstants.TRANSPORT_OK) {
1238 backupDataName.delete();
1239 newStateName.renameTo(savedStateName);
1240 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1241 } else {
1242 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1243 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001244 } catch (Exception e) {
1245 Log.e(TAG, "Transport error backing up " + packageName, e);
1246 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001247 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001248 } finally {
1249 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001250 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001251
Dan Egnor01445162009-09-21 17:04:05 -07001252 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001253 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001254 }
1255
Christopher Tatedf01dea2009-06-09 20:45:02 -07001256
1257 // ----- Restore handling -----
1258
Christopher Tateabce4e82009-06-18 18:35:32 -07001259 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001260 // Allow unsigned apps, but not signed on one device and unsigned on the other
1261 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001262 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1263 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001264 if ((storedSigs == null || storedSigs.length == 0)
1265 && (deviceSigs == null || deviceSigs.length == 0)) {
1266 return true;
1267 }
1268 if (storedSigs == null || deviceSigs == null) {
1269 return false;
1270 }
1271
Christopher Tateabce4e82009-06-18 18:35:32 -07001272 // !!! TODO: this demands that every stored signature match one
1273 // that is present on device, and does not demand the converse.
1274 // Is this this right policy?
1275 int nStored = storedSigs.length;
1276 int nDevice = deviceSigs.length;
1277
1278 for (int i=0; i < nStored; i++) {
1279 boolean match = false;
1280 for (int j=0; j < nDevice; j++) {
1281 if (storedSigs[i].equals(deviceSigs[j])) {
1282 match = true;
1283 break;
1284 }
1285 }
1286 if (!match) {
1287 return false;
1288 }
1289 }
1290 return true;
1291 }
1292
Christopher Tatedf01dea2009-06-09 20:45:02 -07001293 class PerformRestoreThread extends Thread {
1294 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001295 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001296 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001297 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001298
Christopher Tate5cbbf562009-06-22 16:44:51 -07001299 class RestoreRequest {
1300 public PackageInfo app;
1301 public int storedAppVersion;
1302
1303 RestoreRequest(PackageInfo _app, int _version) {
1304 app = _app;
1305 storedAppVersion = _version;
1306 }
1307 }
1308
Christopher Tate7d562ec2009-06-25 18:03:43 -07001309 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001310 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001311 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001312 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001313 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001314 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001315
1316 try {
1317 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1318 } catch (RemoteException e) {
1319 // can't happen; the transport is local
1320 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001321 }
1322
1323 @Override
1324 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001325 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001326 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001327 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001328 /**
1329 * Restore sequence:
1330 *
Dan Egnorefe52642009-06-24 00:16:33 -07001331 * 1. get the restore set description for our identity
1332 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001333 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001334 * 3. for each app in the restore queue:
1335 * 3.a. clear the app data
1336 * 3.b. get the restore data for the app from the transport
1337 * 3.c. launch the backup agent for the app
1338 * 3.d. agent.doRestore() with the data from the server
1339 * 3.e. unbind the agent [and kill the app?]
1340 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001341 *
1342 * On errors, we try our best to recover and move on to the next
1343 * application, but if necessary we abort the whole operation --
1344 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001345 */
1346
Christopher Tate7d562ec2009-06-25 18:03:43 -07001347 int error = -1; // assume error
1348
Dan Egnorefe52642009-06-24 00:16:33 -07001349 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001350 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001351 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001352 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001353
Dan Egnorefe52642009-06-24 00:16:33 -07001354 // Get the list of all packages which have backup enabled.
1355 // (Include the Package Manager metadata pseudo-package first.)
1356 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1357 PackageInfo omPackage = new PackageInfo();
1358 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1359 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001360
Dan Egnorefe52642009-06-24 00:16:33 -07001361 List<PackageInfo> agentPackages = allAgentPackages();
1362 restorePackages.addAll(agentPackages);
1363
Christopher Tate7d562ec2009-06-25 18:03:43 -07001364 // let the observer know that we're running
1365 if (mObserver != null) {
1366 try {
1367 // !!! TODO: get an actual count from the transport after
1368 // its startRestore() runs?
1369 mObserver.restoreStarting(restorePackages.size());
1370 } catch (RemoteException e) {
1371 Log.d(TAG, "Restore observer died at restoreStarting");
1372 mObserver = null;
1373 }
1374 }
1375
Dan Egnor01445162009-09-21 17:04:05 -07001376 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1377 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001378 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001379 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001380 return;
1381 }
1382
1383 String packageName = mTransport.nextRestorePackage();
1384 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001385 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001386 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001387 return;
1388 } else if (packageName.equals("")) {
1389 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001390 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1391 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001392 return;
1393 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1394 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1395 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001396 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1397 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001398 return;
1399 }
1400
1401 // Pull the Package Manager metadata from the restore set first
1402 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1403 mPackageManager, agentPackages);
1404 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1405
Christopher Tate8c032472009-07-02 14:28:47 -07001406 // Verify that the backup set includes metadata. If not, we can't do
1407 // signature/version verification etc, so we simply do not proceed with
1408 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001409 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001410 Log.e(TAG, "No restore metadata available, so not restoring settings");
1411 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1412 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001413 return;
1414 }
1415
Christopher Tate7d562ec2009-06-25 18:03:43 -07001416 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001417 for (;;) {
1418 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001419
Dan Egnorefe52642009-06-24 00:16:33 -07001420 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001421 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001422 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001423 return;
1424 } else if (packageName.equals("")) {
1425 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001426 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001427
Christopher Tate7d562ec2009-06-25 18:03:43 -07001428 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001429 try {
1430 mObserver.onUpdate(count);
1431 } catch (RemoteException e) {
1432 Log.d(TAG, "Restore observer died in onUpdate");
1433 mObserver = null;
1434 }
1435 }
1436
Dan Egnorefe52642009-06-24 00:16:33 -07001437 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1438 if (metaInfo == null) {
1439 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1441 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001442 continue;
1443 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001444
Dan Egnorbb9001c2009-07-27 12:20:13 -07001445 PackageInfo packageInfo;
1446 try {
1447 int flags = PackageManager.GET_SIGNATURES;
1448 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1449 } catch (NameNotFoundException e) {
1450 Log.e(TAG, "Invalid package restoring data", e);
1451 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1452 "Package missing on device");
1453 continue;
1454 }
1455
Dan Egnorefe52642009-06-24 00:16:33 -07001456 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001457 String message = "Version " + metaInfo.versionCode
1458 + " > installed version " + packageInfo.versionCode;
1459 Log.w(TAG, "Package " + packageName + ": " + message);
1460 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001461 continue;
1462 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001463
Dan Egnorefe52642009-06-24 00:16:33 -07001464 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1465 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1467 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001468 continue;
1469 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001470
Dan Egnorefe52642009-06-24 00:16:33 -07001471 if (DEBUG) Log.v(TAG, "Package " + packageName
1472 + " restore version [" + metaInfo.versionCode
1473 + "] is compatible with installed version ["
1474 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001475
Christopher Tate5e1ab332009-09-01 20:32:49 -07001476 // Now perform the actual restore: first clear the app's data
1477 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001478 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001479
1480 // Then set up and bind the agent (with a restricted Application object
1481 // unless the application says otherwise)
1482 boolean useRealApp = (packageInfo.applicationInfo.flags
1483 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1484 if (DEBUG && useRealApp) {
1485 Log.v(TAG, "agent requires real Application subclass for restore");
1486 }
Dan Egnorefe52642009-06-24 00:16:33 -07001487 IBackupAgent agent = bindToAgentSynchronous(
1488 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001489 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1490 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001491 if (agent == null) {
1492 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001493 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1494 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001495 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001496 }
1497
Christopher Tate5e1ab332009-09-01 20:32:49 -07001498 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001499 try {
1500 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001501 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001502 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001503 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001504 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001505
1506 // The agent was probably running with a stub Application object,
1507 // which isn't a valid run mode for the main app logic. Shut
1508 // down the app so that next time it's launched, it gets the
1509 // usual full initialization.
1510 if ((packageInfo.applicationInfo.flags
1511 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1512 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1513 + packageInfo.applicationInfo.processName);
1514 mActivityManager.killApplicationProcess(
1515 packageInfo.applicationInfo.processName,
1516 packageInfo.applicationInfo.uid);
1517 }
Dan Egnorefe52642009-06-24 00:16:33 -07001518 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001519 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001520
1521 // if we get this far, report success to the observer
1522 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001523 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1524 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1525 } catch (Exception e) {
1526 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001527 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001528 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1529
Dan Egnorefe52642009-06-24 00:16:33 -07001530 try {
1531 mTransport.finishRestore();
1532 } catch (RemoteException e) {
1533 Log.e(TAG, "Error finishing restore", e);
1534 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001535
1536 if (mObserver != null) {
1537 try {
1538 mObserver.restoreFinished(error);
1539 } catch (RemoteException e) {
1540 Log.d(TAG, "Restore observer died at restoreFinished");
1541 }
1542 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001543
1544 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001545 synchronized (mQueueLock) {
1546 mBackupOrRestoreInProgress = false;
1547 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001548 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001549 }
1550 }
1551
Dan Egnorefe52642009-06-24 00:16:33 -07001552 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1553 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001554 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555 final String packageName = app.packageName;
1556
Dan Egnorbb9001c2009-07-27 12:20:13 -07001557 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001558
Christopher Tate0749dcd2009-08-13 15:13:03 -07001559 // Don't restore to unprivileged packages
1560 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1561 packageName) != PackageManager.PERMISSION_GRANTED) {
1562 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1563 }
1564
Christopher Tatec7b31e32009-06-10 15:49:30 -07001565 // !!! TODO: get the dirs from the transport
1566 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001567 File newStateName = new File(mStateDir, packageName + ".new");
1568 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001569
Dan Egnorbb9001c2009-07-27 12:20:13 -07001570 ParcelFileDescriptor backupData = null;
1571 ParcelFileDescriptor newState = null;
1572
1573 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001575 backupData = ParcelFileDescriptor.open(backupDataName,
1576 ParcelFileDescriptor.MODE_READ_WRITE |
1577 ParcelFileDescriptor.MODE_CREATE |
1578 ParcelFileDescriptor.MODE_TRUNCATE);
1579
Dan Egnor01445162009-09-21 17:04:05 -07001580 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001581 Log.e(TAG, "Error getting restore data for " + packageName);
1582 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1583 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001584 }
1585
1586 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001587 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001588 backupData = ParcelFileDescriptor.open(backupDataName,
1589 ParcelFileDescriptor.MODE_READ_ONLY);
1590
Dan Egnorbb9001c2009-07-27 12:20:13 -07001591 newState = ParcelFileDescriptor.open(newStateName,
1592 ParcelFileDescriptor.MODE_READ_WRITE |
1593 ParcelFileDescriptor.MODE_CREATE |
1594 ParcelFileDescriptor.MODE_TRUNCATE);
1595
1596 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001597
1598 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001599 //
1600 // !!! TODO: the restored data should be migrated on the server
1601 // side into the current dataset. In that case the new state file
1602 // we just created would reflect the data already extant in the
1603 // backend, so there'd be nothing more to do. Until that happens,
1604 // however, we need to make sure that we record the data to the
1605 // current backend dataset. (Yes, this means shipping the data over
1606 // the wire in both directions. That's bad, but consistency comes
1607 // first, then efficiency.) Once we introduce server-side data
1608 // migration to the newly-restored device's dataset, we will change
1609 // the following from a discard of the newly-written state to the
1610 // "correct" operation of renaming into the canonical state blob.
1611 newStateName.delete(); // TODO: remove; see above comment
1612 //newStateName.renameTo(savedStateName); // TODO: replace with this
1613
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614 int size = (int) backupDataName.length();
1615 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001616 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001617 Log.e(TAG, "Error restoring data for " + packageName, e);
1618 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1619
Christopher Tate96733042009-07-20 14:49:13 -07001620 // If the agent fails restore, it might have put the app's data
1621 // into an incoherent state. For consistency we wipe its data
1622 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001623 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001624 } finally {
1625 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001626 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1627 try { if (newState != null) newState.close(); } catch (IOException e) {}
1628 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001629 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001630 }
1631 }
1632
Christopher Tateee0e78a2009-07-02 11:17:03 -07001633 class PerformClearThread extends Thread {
1634 IBackupTransport mTransport;
1635 PackageInfo mPackage;
1636
1637 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1638 mTransport = transport;
1639 mPackage = packageInfo;
1640 }
1641
1642 @Override
1643 public void run() {
1644 try {
1645 // Clear the on-device backup state to ensure a full backup next time
1646 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1647 File stateFile = new File(stateDir, mPackage.packageName);
1648 stateFile.delete();
1649
1650 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001651 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001652 mTransport.clearBackupData(mPackage);
1653 } catch (RemoteException e) {
1654 // can't happen; the transport is local
1655 } finally {
1656 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001657 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001658 mTransport.finishBackup();
1659 } catch (RemoteException e) {
1660 // can't happen; the transport is local
1661 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001662
1663 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001664 synchronized (mQueueLock) {
1665 mBackupOrRestoreInProgress = false;
1666 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001667 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001668 }
1669 }
1670 }
1671
Christopher Tate4cc86e12009-09-21 19:36:51 -07001672 class PerformInitializeThread extends Thread {
1673 HashSet<String> mQueue;
1674
1675 PerformInitializeThread(HashSet<String> transportNames) {
1676 mQueue = transportNames;
1677 }
1678
1679 @Override
1680 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001681 try {
1682 for (String transportName : mQueue) {
1683 IBackupTransport transport = getTransport(transportName);
1684 if (transport == null) {
1685 Log.e(TAG, "Requested init for " + transportName + " but not found");
1686 continue;
1687 }
1688
Dan Egnor726247c2009-09-29 19:12:31 -07001689 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
1690 EventLog.writeEvent(BACKUP_START_EVENT, transport.transportDirName());
1691 long startRealtime = SystemClock.elapsedRealtime();
1692 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001693
Christopher Tate4cc86e12009-09-21 19:36:51 -07001694 if (status == BackupConstants.TRANSPORT_OK) {
1695 status = transport.finishBackup();
1696 }
1697
1698 // Okay, the wipe really happened. Clean up our local bookkeeping.
1699 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001700 Log.i(TAG, "Device init successful");
1701 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1702 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1703 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
1704 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001705 synchronized (mQueueLock) {
1706 recordInitPendingLocked(false, transportName);
1707 }
Dan Egnor726247c2009-09-29 19:12:31 -07001708 } else {
1709 // If this didn't work, requeue this one and try again
1710 // after a suitable interval
1711 Log.e(TAG, "Transport error in initializeDevice()");
1712 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001713 synchronized (mQueueLock) {
1714 recordInitPendingLocked(true, transportName);
1715 }
1716 // do this via another alarm to make sure of the wakelock states
1717 long delay = transport.requestBackupTime();
1718 if (DEBUG) Log.w(TAG, "init failed on "
1719 + transportName + " resched in " + delay);
1720 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1721 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001722 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001723 }
1724 } catch (RemoteException e) {
1725 // can't happen; the transports are local
1726 } catch (Exception e) {
1727 Log.e(TAG, "Unexpected error performing init", e);
1728 } finally {
1729 // Done; indicate that we're finished and release the wakelock
1730 synchronized (mQueueLock) {
1731 mInitInProgress = false;
1732 }
1733 mWakelock.release();
1734 }
1735 }
1736 }
1737
Christopher Tatedf01dea2009-06-09 20:45:02 -07001738
Christopher Tate487529a2009-04-29 14:03:25 -07001739 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001740
Dan Egnor852f8e42009-09-30 11:20:45 -07001741 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001742 // Record that we need a backup pass for the caller. Since multiple callers
1743 // may share a uid, we need to note all candidates within that uid and schedule
1744 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001745 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001746
Christopher Tate63d27002009-06-16 17:16:42 -07001747 // If the caller does not hold the BACKUP permission, it can only request a
1748 // backup of its own data.
1749 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001750 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001751 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1752 targets = mBackupParticipants.get(Binder.getCallingUid());
1753 } else {
1754 // a caller with full permission can ask to back up any participating app
1755 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001756 targets = new HashSet<ApplicationInfo>();
1757 int N = mBackupParticipants.size();
1758 for (int i = 0; i < N; i++) {
1759 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1760 if (s != null) {
1761 targets.addAll(s);
1762 }
1763 }
1764 }
Christopher Tate487529a2009-04-29 14:03:25 -07001765 if (targets != null) {
1766 synchronized (mQueueLock) {
1767 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001768 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001769 // validate the caller-supplied package name against the known set of
1770 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001771 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001772 // Add the caller to the set of pending backups. If there is
1773 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001774 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001775 if (mPendingBackups.put(app, req) == null) {
1776 // Journal this request in case of crash. The put()
1777 // operation returned null when this package was not already
1778 // in the set; we want to avoid touching the disk redundantly.
1779 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001780
Christopher Tate22b60d82009-07-07 16:36:02 -07001781 if (DEBUG) {
1782 int numKeys = mPendingBackups.size();
1783 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1784 for (BackupRequest b : mPendingBackups.values()) {
1785 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1786 }
1787 }
1788 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001789 }
1790 }
Christopher Tate487529a2009-04-29 14:03:25 -07001791 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001792 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001793 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1794 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001795 }
1796 }
Christopher Tate46758122009-05-06 11:22:00 -07001797
Christopher Tatecde87f42009-06-12 12:55:53 -07001798 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001799 RandomAccessFile out = null;
1800 try {
1801 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1802 out = new RandomAccessFile(mJournal, "rws");
1803 out.seek(out.length());
1804 out.writeUTF(str);
1805 } catch (IOException e) {
1806 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1807 mJournal = null;
1808 } finally {
1809 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001810 }
1811 }
1812
Christopher Tateee0e78a2009-07-02 11:17:03 -07001813 // Clear the given package's backup data from the current transport
1814 public void clearBackupData(String packageName) {
1815 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1816 PackageInfo info;
1817 try {
1818 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1819 } catch (NameNotFoundException e) {
1820 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1821 return;
1822 }
1823
1824 // If the caller does not hold the BACKUP permission, it can only request a
1825 // wipe of its own backed-up data.
1826 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001827 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001828 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1829 apps = mBackupParticipants.get(Binder.getCallingUid());
1830 } else {
1831 // a caller with full permission can ask to back up any participating app
1832 // !!! TODO: allow data-clear of ANY app?
1833 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1834 apps = new HashSet<ApplicationInfo>();
1835 int N = mBackupParticipants.size();
1836 for (int i = 0; i < N; i++) {
1837 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1838 if (s != null) {
1839 apps.addAll(s);
1840 }
1841 }
1842 }
1843
1844 // now find the given package in the set of candidate apps
1845 for (ApplicationInfo app : apps) {
1846 if (app.packageName.equals(packageName)) {
1847 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1848 // found it; fire off the clear request
1849 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001850 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001851 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001852 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1853 new ClearParams(getTransport(mCurrentTransport), info));
1854 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001855 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001856 }
1857 break;
1858 }
1859 }
1860 }
1861
Christopher Tateace7f092009-06-15 18:07:25 -07001862 // Run a backup pass immediately for any applications that have declared
1863 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001864 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001865 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001866
Christopher Tateace7f092009-06-15 18:07:25 -07001867 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001868 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001869 // Because the alarms we are using can jitter, and we want an *immediate*
1870 // backup pass to happen, we restart the timer beginning with "next time,"
1871 // then manually fire the backup trigger intent ourselves.
1872 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001873 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001874 mRunBackupIntent.send();
1875 } catch (PendingIntent.CanceledException e) {
1876 // should never happen
1877 Log.e(TAG, "run-backup intent cancelled!");
1878 }
Christopher Tate46758122009-05-06 11:22:00 -07001879 }
1880 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001881
Christopher Tate8031a3d2009-07-06 16:36:05 -07001882 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001883 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001884 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1885 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001886
Christopher Tate4cc86e12009-09-21 19:36:51 -07001887 Log.i(TAG, "Backup enabled => " + enable);
1888
Christopher Tate6ef58a12009-06-29 14:56:28 -07001889 boolean wasEnabled = mEnabled;
1890 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001891 Settings.Secure.putInt(mContext.getContentResolver(),
1892 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001893 mEnabled = enable;
1894 }
1895
Christopher Tate49401dd2009-07-01 12:34:29 -07001896 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001897 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001898 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001899 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001900 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001901 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001902 if (DEBUG) Log.i(TAG, "Opting out of backup");
1903
Christopher Tateb6787f22009-07-02 17:40:45 -07001904 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001905
1906 // This also constitutes an opt-out, so we wipe any data for
1907 // this device from the backend. We start that process with
1908 // an alarm in order to guarantee wakelock states.
1909 if (wasEnabled && mProvisioned) {
1910 // NOTE: we currently flush every registered transport, not just
1911 // the currently-active one.
1912 HashSet<String> allTransports;
1913 synchronized (mTransports) {
1914 allTransports = new HashSet<String>(mTransports.keySet());
1915 }
1916 // build the set of transports for which we are posting an init
1917 for (String transport : allTransports) {
1918 recordInitPendingLocked(true, transport);
1919 }
1920 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1921 mRunInitIntent);
1922 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001923 }
1924 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001925 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001926
Christopher Tate8031a3d2009-07-06 16:36:05 -07001927 // Mark the backup service as having been provisioned
1928 public void setBackupProvisioned(boolean available) {
1929 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1930 "setBackupProvisioned");
1931
1932 boolean wasProvisioned = mProvisioned;
1933 synchronized (this) {
1934 Settings.Secure.putInt(mContext.getContentResolver(),
1935 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1936 mProvisioned = available;
1937 }
1938
1939 synchronized (mQueueLock) {
1940 if (available && !wasProvisioned && mEnabled) {
1941 // we're now good to go, so start the backup alarms
1942 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1943 } else if (!available) {
1944 // No longer enabled, so stop running backups
1945 Log.w(TAG, "Backup service no longer provisioned");
1946 mAlarmManager.cancel(mRunBackupIntent);
1947 }
1948 }
1949 }
1950
1951 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1952 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1953 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1954 BACKUP_INTERVAL, mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001955 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001956 }
1957
Christopher Tate6ef58a12009-06-29 14:56:28 -07001958 // Report whether the backup mechanism is currently enabled
1959 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001960 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001961 return mEnabled; // no need to synchronize just to read it
1962 }
1963
Christopher Tate91717492009-06-26 21:07:13 -07001964 // Report the name of the currently active transport
1965 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001966 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001967 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001968 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001969 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001970 }
1971
Christopher Tate91717492009-06-26 21:07:13 -07001972 // Report all known, available backup transports
1973 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001974 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001975
Christopher Tate91717492009-06-26 21:07:13 -07001976 String[] list = null;
1977 ArrayList<String> known = new ArrayList<String>();
1978 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1979 if (entry.getValue() != null) {
1980 known.add(entry.getKey());
1981 }
1982 }
1983
1984 if (known.size() > 0) {
1985 list = new String[known.size()];
1986 known.toArray(list);
1987 }
1988 return list;
1989 }
1990
1991 // Select which transport to use for the next backup operation. If the given
1992 // name is not one of the available transports, no action is taken and the method
1993 // returns null.
1994 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04001995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001996
1997 synchronized (mTransports) {
1998 String prevTransport = null;
1999 if (mTransports.get(transport) != null) {
2000 prevTransport = mCurrentTransport;
2001 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002002 Settings.Secure.putString(mContext.getContentResolver(),
2003 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002004 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2005 + " returning " + prevTransport);
2006 } else {
2007 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2008 }
2009 return prevTransport;
2010 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002011 }
2012
2013 // Callback: a requested backup agent has been instantiated. This should only
2014 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002015 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002016 synchronized(mAgentConnectLock) {
2017 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2018 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2019 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2020 mConnectedAgent = agent;
2021 mConnecting = false;
2022 } else {
2023 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2024 + " claiming agent connected");
2025 }
2026 mAgentConnectLock.notifyAll();
2027 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002028 }
2029
2030 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2031 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002032 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002033 public void agentDisconnected(String packageName) {
2034 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002035 synchronized(mAgentConnectLock) {
2036 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2037 mConnectedAgent = null;
2038 mConnecting = false;
2039 } else {
2040 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2041 + " claiming agent disconnected");
2042 }
2043 mAgentConnectLock.notifyAll();
2044 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002045 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002046
Christopher Tate8c850b72009-06-07 19:33:20 -07002047 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002048 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002050
2051 synchronized(this) {
2052 if (mActiveRestoreSession != null) {
2053 Log.d(TAG, "Restore session requested but one already active");
2054 return null;
2055 }
Christopher Tate91717492009-06-26 21:07:13 -07002056 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002057 }
2058 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002059 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002060
Christopher Tate9b3905c2009-06-08 15:24:01 -07002061 // ----- Restore session -----
2062
2063 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002064 private static final String TAG = "RestoreSession";
2065
Christopher Tate9b3905c2009-06-08 15:24:01 -07002066 private IBackupTransport mRestoreTransport = null;
2067 RestoreSet[] mRestoreSets = null;
2068
Christopher Tate91717492009-06-26 21:07:13 -07002069 RestoreSession(String transport) {
2070 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002071 }
2072
2073 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002074 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002076 "getAvailableRestoreSets");
2077
Christopher Tatef68eb502009-06-16 11:02:01 -07002078 try {
Christopher Tate43383042009-07-13 15:17:13 -07002079 if (mRestoreTransport == null) {
2080 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002081 return null;
2082 }
2083 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002084 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002085 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002086 }
2087 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002088 } catch (Exception e) {
2089 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2090 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002091 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002092 }
2093
Dan Egnor0084da52009-07-29 12:57:16 -07002094 public synchronized int performRestore(long token, IRestoreObserver observer) {
2095 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2096 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002097
Christopher Tatef2c321a2009-08-10 15:43:36 -07002098 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2099 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002100
Dan Egnor0084da52009-07-29 12:57:16 -07002101 if (mRestoreTransport == null || mRestoreSets == null) {
2102 Log.e(TAG, "Ignoring performRestore() with no restore set");
2103 return -1;
2104 }
2105
Christopher Tate21ab6a52009-09-24 18:01:46 -07002106 synchronized (mQueueLock) {
2107 if (mBackupOrRestoreInProgress) {
2108 Log.e(TAG, "Backup pass in progress, restore aborted");
2109 return -1;
2110 }
2111
2112 for (int i = 0; i < mRestoreSets.length; i++) {
2113 if (token == mRestoreSets[i].token) {
2114 long oldId = Binder.clearCallingIdentity();
2115 // Suppress backups until the restore operation is finished
2116 mBackupOrRestoreInProgress = true;
2117 mWakelock.acquire();
2118 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2119 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2120 mBackupHandler.sendMessage(msg);
2121 Binder.restoreCallingIdentity(oldId);
2122 return 0;
2123 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002124 }
2125 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002126
2127 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002128 return -1;
2129 }
2130
Dan Egnor0084da52009-07-29 12:57:16 -07002131 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002132 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002133 "endRestoreSession");
2134
Dan Egnor0084da52009-07-29 12:57:16 -07002135 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002136
Dan Egnor0084da52009-07-29 12:57:16 -07002137 synchronized (this) {
2138 try {
2139 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2140 } catch (Exception e) {
2141 Log.e(TAG, "Error in finishRestore", e);
2142 } finally {
2143 mRestoreTransport = null;
2144 }
2145 }
2146
2147 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002148 if (BackupManagerService.this.mActiveRestoreSession == this) {
2149 BackupManagerService.this.mActiveRestoreSession = null;
2150 } else {
2151 Log.e(TAG, "ending non-current restore session");
2152 }
2153 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002154 }
2155 }
2156
Christopher Tate043dadc2009-06-02 16:11:00 -07002157
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002158 @Override
2159 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2160 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002161 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002162 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2163 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2164 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2165 + (!mInitInProgress ? "not " : "") + "initializing");
2166 pw.println("Last backup pass: " + mLastBackupPass
2167 + " (now = " + System.currentTimeMillis() + ')');
2168 pw.println(" next scheduled: " + mNextBackupPass);
2169
Christopher Tate91717492009-06-26 21:07:13 -07002170 pw.println("Available transports:");
2171 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002172 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2173 try {
2174 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2175 for (File f : dir.listFiles()) {
2176 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2177 }
2178 } catch (RemoteException e) {
2179 Log.e(TAG, "Error in transportDirName()", e);
2180 pw.println(" Error: " + e);
2181 }
Christopher Tate91717492009-06-26 21:07:13 -07002182 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002183
2184 pw.println("Pending init: " + mPendingInits.size());
2185 for (String s : mPendingInits) {
2186 pw.println(" " + s);
2187 }
2188
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002189 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002190 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002191 for (int i=0; i<N; i++) {
2192 int uid = mBackupParticipants.keyAt(i);
2193 pw.print(" uid: ");
2194 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002195 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2196 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002197 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002198 }
2199 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002200
Christopher Tate73e02522009-07-15 14:18:26 -07002201 pw.println("Ever backed up: " + mEverStoredApps.size());
2202 for (String pkg : mEverStoredApps) {
2203 pw.println(" " + pkg);
2204 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002205
2206 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002207 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002208 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002209 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002210 }
2211 }
Christopher Tate487529a2009-04-29 14:03:25 -07002212}