blob: ef0cbeeb372b437555afa15dcea3c63ce4b7b4af [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070049import android.os.SystemClock;
50import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.util.Log;
52import android.util.SparseArray;
53
54import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070055import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070056import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070057import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070058
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070060import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tate6785dd82009-06-18 15:58:25 -070063import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
82 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Christopher Tate8031a3d2009-07-06 16:36:05 -070088 // The amount of time between the initial provisioning of the device and
89 // the first backup pass.
90 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
91
Christopher Tate4cc86e12009-09-21 19:36:51 -070092 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
93 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
94 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070095 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070096 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070097 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070098 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -070099 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700100
Dan Egnorbb9001c2009-07-27 12:20:13 -0700101 // Event tags -- see system/core/logcat/event-log-tags
102 private static final int BACKUP_DATA_CHANGED_EVENT = 2820;
103 private static final int BACKUP_START_EVENT = 2821;
104 private static final int BACKUP_TRANSPORT_FAILURE_EVENT = 2822;
105 private static final int BACKUP_AGENT_FAILURE_EVENT = 2823;
106 private static final int BACKUP_PACKAGE_EVENT = 2824;
107 private static final int BACKUP_SUCCESS_EVENT = 2825;
Christopher Tated55e18a2009-09-21 10:12:59 -0700108 private static final int BACKUP_RESET_EVENT = 2826;
Dan 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;
208 RandomAccessFile mJournalStream;
209
210 // Keep a log of all the apps we've ever backed up
211 private File mEverStored;
212 private RandomAccessFile mEverStoredStream;
213 HashSet<String> mEverStoredApps = new HashSet<String>();
214
Christopher Tate4cc86e12009-09-21 19:36:51 -0700215 // Persistently track the need to do a full init
216 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
217 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700218 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700219
Christopher Tate487529a2009-04-29 14:03:25 -0700220 public BackupManagerService(Context context) {
221 mContext = context;
222 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700223 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700224
Christopher Tateb6787f22009-07-02 17:40:45 -0700225 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
226 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
227
Christopher Tate22b87872009-05-04 16:41:53 -0700228 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700229 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700230 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700231 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700232 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700233 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700234 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700235
Christopher Tate4cc86e12009-09-21 19:36:51 -0700236 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700237 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700238 IntentFilter filter = new IntentFilter();
239 filter.addAction(RUN_BACKUP_ACTION);
240 context.registerReceiver(mRunBackupReceiver, filter,
241 android.Manifest.permission.BACKUP, null);
242
243 mRunInitReceiver = new RunInitializeReceiver();
244 filter = new IntentFilter();
245 filter.addAction(RUN_INITIALIZE_ACTION);
246 context.registerReceiver(mRunInitReceiver, filter,
247 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700248
249 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700250 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
251 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
252
Christopher Tate4cc86e12009-09-21 19:36:51 -0700253 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
254 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
255 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
256
Christopher Tatecde87f42009-06-12 12:55:53 -0700257 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700258 mJournalDir = new File(mBaseStateDir, "pending");
259 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700260 makeJournalLocked(); // okay because no other threads are running yet
261
Christopher Tate73e02522009-07-15 14:18:26 -0700262 // Set up the various sorts of package tracking we do
263 initPackageTracking();
264
Christopher Tateabce4e82009-06-18 18:35:32 -0700265 // Build our mapping of uid to backup client services. This implicitly
266 // schedules a backup pass on the Package Manager metadata the first
267 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700268 synchronized (mBackupParticipants) {
269 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700270 }
271
Dan Egnor87a02bc2009-06-17 02:30:10 -0700272 // Set up our transport options and initialize the default transport
273 // TODO: Have transports register themselves somehow?
274 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700275 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700276 ComponentName localName = new ComponentName(context, LocalTransport.class);
277 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700278
Christopher Tate91717492009-06-26 21:07:13 -0700279 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700280 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
281 Settings.Secure.BACKUP_TRANSPORT);
282 if ("".equals(mCurrentTransport)) {
283 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700284 }
Christopher Tate91717492009-06-26 21:07:13 -0700285 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
286
287 // Attach to the Google backup transport. When this comes up, it will set
288 // itself as the current transport because we explicitly reset mCurrentTransport
289 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700290 Intent intent = new Intent().setComponent(new ComponentName(
291 "com.google.android.backup",
292 "com.google.android.backup.BackupTransportService"));
293 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700294
Christopher Tatecde87f42009-06-12 12:55:53 -0700295 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700296 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700297 parseLeftoverJournals();
298
Christopher Tateb6787f22009-07-02 17:40:45 -0700299 // Power management
300 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
301
302 // Start the backup passes going
303 setBackupEnabled(areEnabled);
304 }
305
306 private class RunBackupReceiver extends BroadcastReceiver {
307 public void onReceive(Context context, Intent intent) {
308 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700309 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700310 if (mPendingInits.size() > 0) {
311 // If there are pending init operations, we process those
312 // and then settle into the usual periodic backup schedule.
313 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
314 try {
315 mAlarmManager.cancel(mRunInitIntent);
316 mRunInitIntent.send();
317 } catch (PendingIntent.CanceledException ce) {
318 Log.e(TAG, "Run init intent cancelled");
319 // can't really do more than bail here
320 }
321 } else {
322 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700323 // fully set up, in the middle of a backup already,
324 // or racing with an initialize pass.
325 if (mEnabled && mProvisioned
326 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700327 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700328 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700329
330 // Acquire the wakelock and pass it to the backup thread. it will
331 // be released once backup concludes.
332 mWakelock.acquire();
333
334 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
335 mBackupHandler.sendMessage(msg);
336 } else {
337 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700338 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700339 }
340 }
341 }
342 }
343 }
344 }
345
346 private class RunInitializeReceiver extends BroadcastReceiver {
347 public void onReceive(Context context, Intent intent) {
348 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
349 synchronized (mQueueLock) {
350 if (DEBUG) Log.v(TAG, "Running a device init");
351 mInitInProgress = true;
352
353 // Acquire the wakelock and pass it to the init thread. it will
354 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700355 mWakelock.acquire();
356
Christopher Tate4cc86e12009-09-21 19:36:51 -0700357 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700358 mBackupHandler.sendMessage(msg);
359 }
360 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700361 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700362 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700363
Christopher Tate73e02522009-07-15 14:18:26 -0700364 private void initPackageTracking() {
365 if (DEBUG) Log.v(TAG, "Initializing package tracking");
366
Christopher Tatee97e8072009-07-15 16:45:50 -0700367 // Keep a log of what apps we've ever backed up. Because we might have
368 // rebooted in the middle of an operation that was removing something from
369 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700370 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700371 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700372 try {
Christopher Tatedfec20b2009-08-03 15:38:09 -0700373 // If there are previous contents, parse them out then start a new
374 // file to continue the recordkeeping.
375 if (mEverStored.exists()) {
376 RandomAccessFile temp = new RandomAccessFile(tempProcessedFile, "rw");
377 mEverStoredStream = new RandomAccessFile(mEverStored, "r");
Christopher Tate73e02522009-07-15 14:18:26 -0700378
Christopher Tatedfec20b2009-08-03 15:38:09 -0700379 // parse its existing contents
380 mEverStoredStream.seek(0);
381 temp.seek(0);
382 try {
383 while (true) {
384 PackageInfo info;
385 String pkg = mEverStoredStream.readUTF();
386 try {
387 info = mPackageManager.getPackageInfo(pkg, 0);
388 mEverStoredApps.add(pkg);
389 temp.writeUTF(pkg);
390 if (DEBUG) Log.v(TAG, " + " + pkg);
391 } catch (NameNotFoundException e) {
392 // nope, this package was uninstalled; don't include it
393 if (DEBUG) Log.v(TAG, " - " + pkg);
394 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700395 }
Christopher Tatedfec20b2009-08-03 15:38:09 -0700396 } catch (EOFException e) {
397 // now we're at EOF
Christopher Tate73e02522009-07-15 14:18:26 -0700398 }
Christopher Tatee97e8072009-07-15 16:45:50 -0700399
Christopher Tatedfec20b2009-08-03 15:38:09 -0700400 // Once we've rewritten the backup history log, atomically replace the
401 // old one with the new one then reopen the file for continuing use.
402 temp.close();
403 mEverStoredStream.close();
404 tempProcessedFile.renameTo(mEverStored);
405 }
406 // This will create the file if it doesn't exist
Christopher Tatee97e8072009-07-15 16:45:50 -0700407 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
Christopher Tatedfec20b2009-08-03 15:38:09 -0700408 mEverStoredStream.seek(mEverStoredStream.length());
Christopher Tate73e02522009-07-15 14:18:26 -0700409 } catch (IOException e) {
410 Log.e(TAG, "Unable to open known-stored file!");
411 mEverStoredStream = null;
412 }
413
Christopher Tatee97e8072009-07-15 16:45:50 -0700414 // If we were in the middle of removing something from the ever-backed-up
415 // file, there might be a transient "processed.new" file still present.
416 // We've reconstructed a coherent state at this point though, so we can
417 // safely discard that file now.
418 if (tempProcessedFile.exists()) {
419 tempProcessedFile.delete();
420 }
421
Christopher Tate73e02522009-07-15 14:18:26 -0700422 // Register for broadcasts about package install, etc., so we can
423 // update the provider list.
424 IntentFilter filter = new IntentFilter();
425 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
426 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
427 filter.addDataScheme("package");
428 mContext.registerReceiver(mBroadcastReceiver, filter);
429 }
430
Christopher Tatecde87f42009-06-12 12:55:53 -0700431 private void makeJournalLocked() {
432 try {
433 mJournal = File.createTempFile("journal", null, mJournalDir);
434 mJournalStream = new RandomAccessFile(mJournal, "rwd");
435 } catch (IOException e) {
436 Log.e(TAG, "Unable to write backup journals");
437 mJournal = null;
438 mJournalStream = null;
439 }
440 }
441
442 private void parseLeftoverJournals() {
443 if (mJournal != null) {
444 File[] allJournals = mJournalDir.listFiles();
445 for (File f : allJournals) {
446 if (f.compareTo(mJournal) != 0) {
447 // This isn't the current journal, so it must be a leftover. Read
448 // out the package names mentioned there and schedule them for
449 // backup.
450 try {
451 Log.i(TAG, "Found stale backup journal, scheduling:");
452 RandomAccessFile in = new RandomAccessFile(f, "r");
453 while (true) {
454 String packageName = in.readUTF();
455 Log.i(TAG, " + " + packageName);
456 dataChanged(packageName);
457 }
458 } catch (EOFException e) {
459 // no more data; we're done
460 } catch (Exception e) {
461 // can't read it or other error; just skip it
462 } finally {
463 // close/delete the file
464 f.delete();
465 }
466 }
467 }
468 }
469 }
470
Christopher Tate4cc86e12009-09-21 19:36:51 -0700471 // Maintain persistent state around whether need to do an initialize operation.
472 // Must be called with the queue lock held.
473 void recordInitPendingLocked(boolean isPending, String transportName) {
474 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
475 + " on transport " + transportName);
476 try {
477 IBackupTransport transport = getTransport(transportName);
478 String transportDirName = transport.transportDirName();
479 File stateDir = new File(mBaseStateDir, transportDirName);
480 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
481
482 if (isPending) {
483 // We need an init before we can proceed with sending backup data.
484 // Record that with an entry in our set of pending inits, as well as
485 // journaling it via creation of a sentinel file.
486 mPendingInits.add(transportName);
487 try {
488 (new FileOutputStream(initPendingFile)).close();
489 } catch (IOException ioe) {
490 // Something is badly wrong with our permissions; just try to move on
491 }
492 } else {
493 // No more initialization needed; wipe the journal and reset our state.
494 initPendingFile.delete();
495 mPendingInits.remove(transportName);
496 }
497 } catch (RemoteException e) {
498 // can't happen; the transport is local
499 }
500 }
501
Christopher Tated55e18a2009-09-21 10:12:59 -0700502 // Reset all of our bookkeeping, in response to having been told that
503 // the backend data has been wiped [due to idle expiry, for example],
504 // so we must re-upload all saved settings.
505 void resetBackupState(File stateFileDir) {
506 synchronized (mQueueLock) {
507 // Wipe the "what we've ever backed up" tracking
508 try {
509 // close the ever-stored journal...
510 if (mEverStoredStream != null) {
511 mEverStoredStream.close();
512 }
513 // ... so we can delete it and start over
514 mEverStored.delete();
515 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
516 } catch (IOException e) {
517 Log.e(TAG, "Unable to open known-stored file!");
518 mEverStoredStream = null;
519 }
520 mEverStoredApps.clear();
521
522 // Remove all the state files
523 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700524 // ... but don't touch the needs-init sentinel
525 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
526 sf.delete();
527 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700528 }
529
530 // Enqueue a new backup of every participant
531 int N = mBackupParticipants.size();
532 for (int i=0; i<N; i++) {
533 int uid = mBackupParticipants.keyAt(i);
534 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
535 for (ApplicationInfo app: participants) {
536 try {
537 dataChanged(app.packageName);
538 } catch (RemoteException e) {
539 // can't happen; we're in the same process
540 }
541 }
542 }
543 }
544 }
545
Christopher Tate91717492009-06-26 21:07:13 -0700546 // Add a transport to our set of available backends
547 private void registerTransport(String name, IBackupTransport transport) {
548 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700549 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700550 mTransports.put(name, transport);
551 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700552
553 // If the init sentinel file exists, we need to be sure to perform the init
554 // as soon as practical. We also create the state directory at registration
555 // time to ensure it's present from the outset.
556 try {
557 String transportName = transport.transportDirName();
558 File stateDir = new File(mBaseStateDir, transportName);
559 stateDir.mkdirs();
560
561 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
562 if (initSentinel.exists()) {
563 synchronized (mQueueLock) {
564 mPendingInits.add(transportName);
565
566 // TODO: pick a better starting time than now + 1 minute
567 long delay = 1000 * 60; // one minute, in milliseconds
568 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
569 System.currentTimeMillis() + delay, mRunInitIntent);
570 }
571 }
572 } catch (RemoteException e) {
573 // can't happen, the transport is local
574 }
Christopher Tate91717492009-06-26 21:07:13 -0700575 }
576
Christopher Tate3799bc22009-05-06 16:13:56 -0700577 // ----- Track installation/removal of packages -----
578 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
579 public void onReceive(Context context, Intent intent) {
580 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
581
582 Uri uri = intent.getData();
583 if (uri == null) {
584 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700585 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700586 String pkgName = uri.getSchemeSpecificPart();
587 if (pkgName == null) {
588 return;
589 }
590
591 String action = intent.getAction();
592 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
593 synchronized (mBackupParticipants) {
594 Bundle extras = intent.getExtras();
595 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
596 // The package was just upgraded
597 updatePackageParticipantsLocked(pkgName);
598 } else {
599 // The package was just added
600 addPackageParticipantsLocked(pkgName);
601 }
602 }
603 }
604 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
605 Bundle extras = intent.getExtras();
606 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
607 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
608 } else {
609 synchronized (mBackupParticipants) {
610 removePackageParticipantsLocked(pkgName);
611 }
612 }
613 }
614 }
615 };
616
Dan Egnor87a02bc2009-06-17 02:30:10 -0700617 // ----- Track connection to GoogleBackupTransport service -----
618 ServiceConnection mGoogleConnection = new ServiceConnection() {
619 public void onServiceConnected(ComponentName name, IBinder service) {
620 if (DEBUG) Log.v(TAG, "Connected to Google transport");
621 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700622 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700623 }
624
625 public void onServiceDisconnected(ComponentName name) {
626 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
627 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700628 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700629 }
630 };
631
Joe Onorato8ad02812009-05-13 01:41:44 -0400632 // ----- Run the actual backup process asynchronously -----
633
Christopher Tate181fafa2009-05-14 11:12:14 -0700634 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400635 public void handleMessage(Message msg) {
636
637 switch (msg.what) {
638 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700639 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700640 mLastBackupPass = System.currentTimeMillis();
641 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
642
Christopher Tate91717492009-06-26 21:07:13 -0700643 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700644 if (transport == null) {
645 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700646 synchronized (mQueueLock) {
647 mBackupOrRestoreInProgress = false;
648 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700649 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700650 break;
651 }
652
Joe Onorato8ad02812009-05-13 01:41:44 -0400653 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700654 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700655 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400656 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700657 // Do we have any work to do?
658 if (mPendingBackups.size() > 0) {
659 for (BackupRequest b: mPendingBackups.values()) {
660 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700661 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700662 Log.v(TAG, "clearing pending backups");
663 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700664
Christopher Tate49401dd2009-07-01 12:34:29 -0700665 // Start a new backup-queue journal file too
666 if (mJournalStream != null) {
667 try {
668 mJournalStream.close();
669 } catch (IOException e) {
670 // don't need to do anything
671 }
672 makeJournalLocked();
673 }
674
675 // At this point, we have started a new journal file, and the old
676 // file identity is being passed to the backup processing thread.
677 // When it completes successfully, that old journal file will be
678 // deleted. If we crash prior to that, the old journal is parsed
679 // at next boot and the journaled requests fulfilled.
680 (new PerformBackupThread(transport, queue, oldJournal)).start();
681 } else {
682 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700683 synchronized (mQueueLock) {
684 mBackupOrRestoreInProgress = false;
685 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700686 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700687 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400688 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700689 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700690 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700691
692 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400693 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700694
695 case MSG_RUN_RESTORE:
696 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700697 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400698 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700699 (new PerformRestoreThread(params.transport, params.observer,
700 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700701 break;
702 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700703
704 case MSG_RUN_CLEAR:
705 {
706 ClearParams params = (ClearParams)msg.obj;
707 (new PerformClearThread(params.transport, params.packageInfo)).start();
708 break;
709 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700710
711 case MSG_RUN_INITIALIZE:
712 {
713 HashSet<String> queue;
714
715 // Snapshot the pending-init queue and work on that
716 synchronized (mQueueLock) {
717 queue = new HashSet<String>(mPendingInits);
718 mPendingInits.clear();
719 }
720
721 (new PerformInitializeThread(queue)).start();
722 break;
723 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400724 }
725 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400726 }
727
Christopher Tate181fafa2009-05-14 11:12:14 -0700728 // Add the backup agents in the given package to our set of known backup participants.
729 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700730 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700731 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700732 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700733 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700734 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700735 }
736
Christopher Tate181fafa2009-05-14 11:12:14 -0700737 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700738 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700739 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700740 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
741 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700742 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700743 + " uid=" + p.applicationInfo.uid
744 + " killAfterRestore="
745 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
746 + " restoreNeedsApplication="
747 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
748 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700749 }
750 }
751
Dan Egnorefe52642009-06-24 00:16:33 -0700752 for (PackageInfo pkg : targetPkgs) {
753 if (packageName == null || pkg.packageName.equals(packageName)) {
754 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700755 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700756 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700757 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700758 mBackupParticipants.put(uid, set);
759 }
Dan Egnorefe52642009-06-24 00:16:33 -0700760 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700761
762 // If we've never seen this app before, schedule a backup for it
763 if (!mEverStoredApps.contains(pkg.packageName)) {
764 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
765 + " never backed up; scheduling");
766 try {
767 dataChanged(pkg.packageName);
768 } catch (RemoteException e) {
769 // can't happen; it's a local method call
770 }
771 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700772 }
Christopher Tate487529a2009-04-29 14:03:25 -0700773 }
774 }
775
Christopher Tate6785dd82009-06-18 15:58:25 -0700776 // Remove the given package's entry from our known active set. If
777 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700778 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700779 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700780 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700781 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700782 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700783 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700784 int flags = PackageManager.GET_SIGNATURES;
785 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700786 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700787 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700788 }
789 } else {
790 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700791 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700792 }
793 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700794 }
795
Joe Onorato8ad02812009-05-13 01:41:44 -0400796 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700797 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700798 if (DEBUG) {
799 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
800 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700801 for (PackageInfo p : agents) {
802 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700803 }
804 }
Dan Egnorefe52642009-06-24 00:16:33 -0700805 for (PackageInfo pkg : agents) {
806 if (packageName == null || pkg.packageName.equals(packageName)) {
807 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700808 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700809 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700810 // Find the existing entry with the same package name, and remove it.
811 // We can't just remove(app) because the instances are different.
812 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700813 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700814 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700815 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700816 break;
817 }
818 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700819 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700820 mBackupParticipants.delete(uid);
821 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700822 }
823 }
824 }
825 }
826
Christopher Tate181fafa2009-05-14 11:12:14 -0700827 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700828 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700829 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700830 int flags = PackageManager.GET_SIGNATURES;
831 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
832 int N = packages.size();
833 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700834 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700835 try {
836 ApplicationInfo app = pkg.applicationInfo;
837 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
838 || app.backupAgentName == null
839 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
840 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
841 packages.remove(a);
842 }
843 else {
844 // we will need the shared library path, so look that up and store it here
845 app = mPackageManager.getApplicationInfo(pkg.packageName,
846 PackageManager.GET_SHARED_LIBRARY_FILES);
847 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
848 }
849 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700850 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700851 }
852 }
Dan Egnorefe52642009-06-24 00:16:33 -0700853 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700854 }
Christopher Tateaa088442009-06-16 18:25:46 -0700855
Christopher Tate3799bc22009-05-06 16:13:56 -0700856 // Reset the given package's known backup participants. Unlike add/remove, the update
857 // action cannot be passed a null package name.
858 void updatePackageParticipantsLocked(String packageName) {
859 if (packageName == null) {
860 Log.e(TAG, "updatePackageParticipants called with null package name");
861 return;
862 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700863 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700864
865 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700866 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700867 removePackageParticipantsLockedInner(packageName, allApps);
868 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700869 }
870
Christopher Tate73e02522009-07-15 14:18:26 -0700871 // Called from the backup thread: record that the given app has been successfully
872 // backed up at least once
873 void logBackupComplete(String packageName) {
Christopher Tatee97e8072009-07-15 16:45:50 -0700874 if (mEverStoredStream != null && !packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate73e02522009-07-15 14:18:26 -0700875 synchronized (mEverStoredApps) {
876 if (mEverStoredApps.add(packageName)) {
877 try {
878 mEverStoredStream.writeUTF(packageName);
879 } catch (IOException e) {
880 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
881 try {
882 mEverStoredStream.close();
883 } catch (IOException ioe) {
884 // we're dropping it; no need to handle an exception on close here
885 }
886 mEverStoredStream = null;
887 }
888 }
889 }
890 }
891 }
892
Christopher Tatee97e8072009-07-15 16:45:50 -0700893 // Remove our awareness of having ever backed up the given package
894 void removeEverBackedUp(String packageName) {
895 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName
896 + ", new set:");
897
898 if (mEverStoredStream != null) {
899 synchronized (mEverStoredApps) {
900 // Rewrite the file and rename to overwrite. If we reboot in the middle,
901 // we'll recognize on initialization time that the package no longer
902 // exists and fix it up then.
903 File tempKnownFile = new File(mBaseStateDir, "processed.new");
904 try {
905 mEverStoredStream.close();
906 RandomAccessFile known = new RandomAccessFile(tempKnownFile, "rw");
907 mEverStoredApps.remove(packageName);
908 for (String s : mEverStoredApps) {
909 known.writeUTF(s);
910 if (DEBUG) Log.v(TAG, " " + s);
911 }
912 known.close();
913 tempKnownFile.renameTo(mEverStored);
914 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
915 } catch (IOException e) {
916 // Bad: we couldn't create the new copy. For safety's sake we
917 // abandon the whole process and remove all what's-backed-up
918 // state entirely, meaning we'll force a backup pass for every
919 // participant on the next boot or [re]install.
920 Log.w(TAG, "Error rewriting backed-up set; halting log");
921 mEverStoredStream = null;
922 mEverStoredApps.clear();
923 tempKnownFile.delete();
924 mEverStored.delete();
925 }
926 }
927 }
928 }
929
Dan Egnor87a02bc2009-06-17 02:30:10 -0700930 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700931 private IBackupTransport getTransport(String transportName) {
932 synchronized (mTransports) {
933 IBackupTransport transport = mTransports.get(transportName);
934 if (transport == null) {
935 Log.w(TAG, "Requested unavailable transport: " + transportName);
936 }
937 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700938 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700939 }
940
Christopher Tatedf01dea2009-06-09 20:45:02 -0700941 // fire off a backup agent, blocking until it attaches or times out
942 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
943 IBackupAgent agent = null;
944 synchronized(mAgentConnectLock) {
945 mConnecting = true;
946 mConnectedAgent = null;
947 try {
948 if (mActivityManager.bindBackupAgent(app, mode)) {
949 Log.d(TAG, "awaiting agent for " + app);
950
951 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700952 // only wait 10 seconds for the clear data to happen
953 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
954 while (mConnecting && mConnectedAgent == null
955 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700956 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700957 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700958 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700959 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700960 return null;
961 }
962 }
963
964 // if we timed out with no connect, abort and move on
965 if (mConnecting == true) {
966 Log.w(TAG, "Timeout waiting for agent " + app);
967 return null;
968 }
969 agent = mConnectedAgent;
970 }
971 } catch (RemoteException e) {
972 // can't happen
973 }
974 }
975 return agent;
976 }
977
Christopher Tatec7b31e32009-06-10 15:49:30 -0700978 // clear an application's data, blocking until the operation completes or times out
979 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700980 // Don't wipe packages marked allowClearUserData=false
981 try {
982 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
983 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
984 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
985 + packageName);
986 return;
987 }
988 } catch (NameNotFoundException e) {
989 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
990 return;
991 }
992
Christopher Tatec7b31e32009-06-10 15:49:30 -0700993 ClearDataObserver observer = new ClearDataObserver();
994
995 synchronized(mClearDataLock) {
996 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700997 /* This is causing some critical processes to be killed during setup.
998 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700999 try {
1000 mActivityManager.clearApplicationUserData(packageName, observer);
1001 } catch (RemoteException e) {
1002 // can't happen because the activity manager is in this process
1003 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001004 */
1005 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001006
1007 // only wait 10 seconds for the clear data to happen
1008 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1009 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1010 try {
1011 mClearDataLock.wait(5000);
1012 } catch (InterruptedException e) {
1013 // won't happen, but still.
1014 mClearingData = false;
1015 }
1016 }
1017 }
1018 }
1019
1020 class ClearDataObserver extends IPackageDataObserver.Stub {
1021 public void onRemoveCompleted(String packageName, boolean succeeded)
Dan Egnor0084da52009-07-29 12:57:16 -07001022 throws RemoteException {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001023 synchronized(mClearDataLock) {
1024 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001025 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001026 }
1027 }
1028 }
1029
Christopher Tate043dadc2009-06-02 16:11:00 -07001030 // ----- Back up a set of applications via a worker thread -----
1031
1032 class PerformBackupThread extends Thread {
1033 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001034 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001035 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001036 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001037 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001038
Christopher Tateaa088442009-06-16 18:25:46 -07001039 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001040 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001041 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001042 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001043 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001044
1045 try {
1046 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1047 } catch (RemoteException e) {
1048 // can't happen; the transport is local
1049 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001050 }
1051
1052 @Override
1053 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001054 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001055 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001056 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1057
Christopher Tate79588342009-06-30 16:11:49 -07001058 // Backups run at background priority
1059 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1060
Christopher Tate043dadc2009-06-02 16:11:00 -07001061 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001062 EventLog.writeEvent(BACKUP_START_EVENT, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001063
1064 // If we haven't stored anything yet, we need to do an init operation.
1065 if (status == BackupConstants.TRANSPORT_OK && mEverStoredApps.size() == 0) {
Dan Egnor726247c2009-09-29 19:12:31 -07001066 Log.i(TAG, "Initializing (wiping) backup transport storage");
Dan Egnor01445162009-09-21 17:04:05 -07001067 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001068 if (status == BackupConstants.TRANSPORT_OK) {
1069 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1070 } else {
1071 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
1072 Log.e(TAG, "Transport error in initializeDevice()");
1073 }
Dan Egnor01445162009-09-21 17:04:05 -07001074 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001075
1076 // The package manager doesn't have a proper <application> etc, but since
1077 // it's running here in the system process we can just set up its agent
1078 // directly and use a synthetic BackupRequest. We always run this pass
1079 // because it's cheap and this way we guarantee that we don't get out of
1080 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001081 if (status == BackupConstants.TRANSPORT_OK) {
1082 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1083 mPackageManager, allAgentPackages());
1084 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1085 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1086 status = processOneBackup(pmRequest,
1087 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1088 }
Christopher Tate90967f42009-09-20 15:28:33 -07001089
Dan Egnor01445162009-09-21 17:04:05 -07001090 if (status == BackupConstants.TRANSPORT_OK) {
1091 // Now run all the backups in our queue
1092 status = doQueuedBackups(mTransport);
1093 }
1094
1095 if (status == BackupConstants.TRANSPORT_OK) {
1096 // Tell the transport to finish everything it has buffered
1097 status = mTransport.finishBackup();
1098 if (status == BackupConstants.TRANSPORT_OK) {
1099 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1100 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, mQueue.size(), millis);
1101 } else {
Dan Egnor726247c2009-09-29 19:12:31 -07001102 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001103 Log.e(TAG, "Transport error in finishBackup()");
1104 }
1105 }
1106
Dan Egnor01445162009-09-21 17:04:05 -07001107 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001108 // The backend reports that our dataset has been wiped. We need to
1109 // reset all of our bookkeeping and instead run a new backup pass for
1110 // everything.
1111 EventLog.writeEvent(BACKUP_RESET_EVENT, mTransport.transportDirName());
1112 resetBackupState(mStateDir);
1113 backupNow();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001114 }
1115 } catch (Exception e) {
1116 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001117 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001118 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001119 // If things went wrong, we need to re-stage the apps we had expected
1120 // to be backing up in this pass. This journals the package names in
1121 // the current active pending-backup file, not in the we are holding
1122 // here in mJournal.
1123 if (status != BackupConstants.TRANSPORT_OK) {
1124 Log.w(TAG, "Backup pass unsuccessful, restaging");
1125 for (BackupRequest req : mQueue) {
1126 try {
1127 dataChanged(req.appInfo.packageName);
1128 } catch (RemoteException e) {
1129 // can't happen; it's a local call
1130 }
1131 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001132
1133 // We also want to reset the backup schedule based on whatever
1134 // the transport suggests by way of retry/backoff time.
1135 try {
1136 startBackupAlarmsLocked(mTransport.requestBackupTime());
1137 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001138 }
1139
1140 // Either backup was successful, in which case we of course do not need
1141 // this pass's journal any more; or it failed, in which case we just
1142 // re-enqueued all of these packages in the current active journal.
1143 // Either way, we no longer need this pass's journal.
1144 if (!mJournal.delete()) {
1145 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1146 }
1147
Christopher Tate21ab6a52009-09-24 18:01:46 -07001148 // Only once we're entirely finished do we indicate our completion
1149 // and release the wakelock
1150 synchronized (mQueueLock) {
1151 mBackupOrRestoreInProgress = false;
1152 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001153 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001154 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001155 }
1156
Dan Egnor01445162009-09-21 17:04:05 -07001157 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001158 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001159 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001160
Christopher Tate0749dcd2009-08-13 15:13:03 -07001161 // Don't run backup, even if requested, if the target app does not have
1162 // the requisite permission
1163 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1164 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1165 Log.w(TAG, "Skipping backup of unprivileged package "
1166 + request.appInfo.packageName);
1167 continue;
1168 }
1169
Christopher Tate043dadc2009-06-02 16:11:00 -07001170 IBackupAgent agent = null;
1171 int mode = (request.fullBackup)
1172 ? IApplicationThread.BACKUP_MODE_FULL
1173 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1174 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001175 agent = bindToAgentSynchronous(request.appInfo, mode);
1176 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001177 int result = processOneBackup(request, agent, transport);
1178 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001179 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001180 } catch (SecurityException ex) {
1181 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001182 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001183 } finally {
1184 try { // unbind even on timeout, just in case
1185 mActivityManager.unbindBackupAgent(request.appInfo);
1186 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001187 }
1188 }
Dan Egnor01445162009-09-21 17:04:05 -07001189
1190 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001191 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001192
Dan Egnor01445162009-09-21 17:04:05 -07001193 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1194 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001195 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001196 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001197
Dan Egnorbb9001c2009-07-27 12:20:13 -07001198 File savedStateName = new File(mStateDir, packageName);
1199 File backupDataName = new File(mDataDir, packageName + ".data");
1200 File newStateName = new File(mStateDir, packageName + ".new");
1201
1202 ParcelFileDescriptor savedState = null;
1203 ParcelFileDescriptor backupData = null;
1204 ParcelFileDescriptor newState = null;
1205
1206 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001207 try {
1208 // Look up the package info & signatures. This is first so that if it
1209 // throws an exception, there's no file setup yet that would need to
1210 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001211 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1212 // The metadata 'package' is synthetic
1213 packInfo = new PackageInfo();
1214 packInfo.packageName = packageName;
1215 } else {
1216 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001217 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001218 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001219
Christopher Tatec7b31e32009-06-10 15:49:30 -07001220 // In a full backup, we pass a null ParcelFileDescriptor as
1221 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001222 if (!request.fullBackup) {
1223 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001224 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001225 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1226 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001227
Dan Egnorbb9001c2009-07-27 12:20:13 -07001228 backupData = ParcelFileDescriptor.open(backupDataName,
1229 ParcelFileDescriptor.MODE_READ_WRITE |
1230 ParcelFileDescriptor.MODE_CREATE |
1231 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001232
Dan Egnorbb9001c2009-07-27 12:20:13 -07001233 newState = ParcelFileDescriptor.open(newStateName,
1234 ParcelFileDescriptor.MODE_READ_WRITE |
1235 ParcelFileDescriptor.MODE_CREATE |
1236 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001237
1238 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001239 agent.doBackup(savedState, backupData, newState);
1240 logBackupComplete(packageName);
1241 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001242 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001243 Log.e(TAG, "Error backing up " + packageName, e);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001244 EventLog.writeEvent(BACKUP_AGENT_FAILURE_EVENT, packageName, e.toString());
1245 backupDataName.delete();
1246 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001247 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001248 } finally {
1249 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1250 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1251 try { if (newState != null) newState.close(); } catch (IOException e) {}
1252 savedState = backupData = newState = null;
1253 }
1254
1255 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001256 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001257 try {
1258 int size = (int) backupDataName.length();
1259 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001260 if (result == BackupConstants.TRANSPORT_OK) {
1261 backupData = ParcelFileDescriptor.open(backupDataName,
1262 ParcelFileDescriptor.MODE_READ_ONLY);
1263 result = transport.performBackup(packInfo, backupData);
1264 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001265
Dan Egnor83861e72009-09-17 16:17:55 -07001266 // TODO - We call finishBackup() for each application backed up, because
1267 // we need to know now whether it succeeded or failed. Instead, we should
1268 // hold off on finishBackup() until the end, which implies holding off on
1269 // renaming *all* the output state files (see below) until that happens.
1270
Dan Egnor01445162009-09-21 17:04:05 -07001271 if (result == BackupConstants.TRANSPORT_OK) {
1272 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001273 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001274 } else {
1275 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1276 }
1277
1278 // After successful transport, delete the now-stale data
1279 // and juggle the files so that next time we supply the agent
1280 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001281 if (result == BackupConstants.TRANSPORT_OK) {
1282 backupDataName.delete();
1283 newStateName.renameTo(savedStateName);
1284 EventLog.writeEvent(BACKUP_PACKAGE_EVENT, packageName, size);
1285 } else {
1286 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
1287 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001288 } catch (Exception e) {
1289 Log.e(TAG, "Transport error backing up " + packageName, e);
1290 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001291 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001292 } finally {
1293 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001294 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001295
Dan Egnor01445162009-09-21 17:04:05 -07001296 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001297 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001298 }
1299
Christopher Tatedf01dea2009-06-09 20:45:02 -07001300
1301 // ----- Restore handling -----
1302
Christopher Tateabce4e82009-06-18 18:35:32 -07001303 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001304 // Allow unsigned apps, but not signed on one device and unsigned on the other
1305 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -07001306 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1307 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001308 if ((storedSigs == null || storedSigs.length == 0)
1309 && (deviceSigs == null || deviceSigs.length == 0)) {
1310 return true;
1311 }
1312 if (storedSigs == null || deviceSigs == null) {
1313 return false;
1314 }
1315
Christopher Tateabce4e82009-06-18 18:35:32 -07001316 // !!! TODO: this demands that every stored signature match one
1317 // that is present on device, and does not demand the converse.
1318 // Is this this right policy?
1319 int nStored = storedSigs.length;
1320 int nDevice = deviceSigs.length;
1321
1322 for (int i=0; i < nStored; i++) {
1323 boolean match = false;
1324 for (int j=0; j < nDevice; j++) {
1325 if (storedSigs[i].equals(deviceSigs[j])) {
1326 match = true;
1327 break;
1328 }
1329 }
1330 if (!match) {
1331 return false;
1332 }
1333 }
1334 return true;
1335 }
1336
Christopher Tatedf01dea2009-06-09 20:45:02 -07001337 class PerformRestoreThread extends Thread {
1338 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001339 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001340 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001341 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001342
Christopher Tate5cbbf562009-06-22 16:44:51 -07001343 class RestoreRequest {
1344 public PackageInfo app;
1345 public int storedAppVersion;
1346
1347 RestoreRequest(PackageInfo _app, int _version) {
1348 app = _app;
1349 storedAppVersion = _version;
1350 }
1351 }
1352
Christopher Tate7d562ec2009-06-25 18:03:43 -07001353 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001354 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001355 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001356 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001357 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001358 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001359
1360 try {
1361 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1362 } catch (RemoteException e) {
1363 // can't happen; the transport is local
1364 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001365 }
1366
1367 @Override
1368 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001369 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001370 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001371 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001372 /**
1373 * Restore sequence:
1374 *
Dan Egnorefe52642009-06-24 00:16:33 -07001375 * 1. get the restore set description for our identity
1376 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001377 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001378 * 3. for each app in the restore queue:
1379 * 3.a. clear the app data
1380 * 3.b. get the restore data for the app from the transport
1381 * 3.c. launch the backup agent for the app
1382 * 3.d. agent.doRestore() with the data from the server
1383 * 3.e. unbind the agent [and kill the app?]
1384 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001385 *
1386 * On errors, we try our best to recover and move on to the next
1387 * application, but if necessary we abort the whole operation --
1388 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001389 */
1390
Christopher Tate7d562ec2009-06-25 18:03:43 -07001391 int error = -1; // assume error
1392
Dan Egnorefe52642009-06-24 00:16:33 -07001393 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001394 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001395 // TODO: Log this before getAvailableRestoreSets, somehow
Dan Egnor313b29f2009-09-22 10:44:10 -07001396 EventLog.writeEvent(RESTORE_START_EVENT, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001397
Dan Egnorefe52642009-06-24 00:16:33 -07001398 // Get the list of all packages which have backup enabled.
1399 // (Include the Package Manager metadata pseudo-package first.)
1400 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1401 PackageInfo omPackage = new PackageInfo();
1402 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1403 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001404
Dan Egnorefe52642009-06-24 00:16:33 -07001405 List<PackageInfo> agentPackages = allAgentPackages();
1406 restorePackages.addAll(agentPackages);
1407
Christopher Tate7d562ec2009-06-25 18:03:43 -07001408 // let the observer know that we're running
1409 if (mObserver != null) {
1410 try {
1411 // !!! TODO: get an actual count from the transport after
1412 // its startRestore() runs?
1413 mObserver.restoreStarting(restorePackages.size());
1414 } catch (RemoteException e) {
1415 Log.d(TAG, "Restore observer died at restoreStarting");
1416 mObserver = null;
1417 }
1418 }
1419
Dan Egnor01445162009-09-21 17:04:05 -07001420 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1421 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001422 Log.e(TAG, "Error starting restore operation");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001423 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001424 return;
1425 }
1426
1427 String packageName = mTransport.nextRestorePackage();
1428 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001429 Log.e(TAG, "Error getting first restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001431 return;
1432 } else if (packageName.equals("")) {
1433 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1435 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001436 return;
1437 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1438 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1439 + "\", found only \"" + packageName + "\"");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1441 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001442 return;
1443 }
1444
1445 // Pull the Package Manager metadata from the restore set first
1446 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1447 mPackageManager, agentPackages);
1448 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1449
Christopher Tate8c032472009-07-02 14:28:47 -07001450 // Verify that the backup set includes metadata. If not, we can't do
1451 // signature/version verification etc, so we simply do not proceed with
1452 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001453 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001454 Log.e(TAG, "No restore metadata available, so not restoring settings");
1455 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, PACKAGE_MANAGER_SENTINEL,
1456 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001457 return;
1458 }
1459
Christopher Tate7d562ec2009-06-25 18:03:43 -07001460 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001461 for (;;) {
1462 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001463
Dan Egnorefe52642009-06-24 00:16:33 -07001464 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001465 Log.e(TAG, "Error getting next restore package");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Dan Egnorefe52642009-06-24 00:16:33 -07001467 return;
1468 } else if (packageName.equals("")) {
1469 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001470 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001471
Christopher Tate7d562ec2009-06-25 18:03:43 -07001472 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001473 try {
1474 mObserver.onUpdate(count);
1475 } catch (RemoteException e) {
1476 Log.d(TAG, "Restore observer died in onUpdate");
1477 mObserver = null;
1478 }
1479 }
1480
Dan Egnorefe52642009-06-24 00:16:33 -07001481 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1482 if (metaInfo == null) {
1483 Log.e(TAG, "Missing metadata for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001484 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1485 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001486 continue;
1487 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001488
Dan Egnorbb9001c2009-07-27 12:20:13 -07001489 PackageInfo packageInfo;
1490 try {
1491 int flags = PackageManager.GET_SIGNATURES;
1492 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1493 } catch (NameNotFoundException e) {
1494 Log.e(TAG, "Invalid package restoring data", e);
1495 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1496 "Package missing on device");
1497 continue;
1498 }
1499
Dan Egnorefe52642009-06-24 00:16:33 -07001500 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001501 String message = "Version " + metaInfo.versionCode
1502 + " > installed version " + packageInfo.versionCode;
1503 Log.w(TAG, "Package " + packageName + ": " + message);
1504 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001505 continue;
1506 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001507
Dan Egnorefe52642009-06-24 00:16:33 -07001508 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1509 Log.w(TAG, "Signature mismatch restoring " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001510 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1511 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001512 continue;
1513 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001514
Dan Egnorefe52642009-06-24 00:16:33 -07001515 if (DEBUG) Log.v(TAG, "Package " + packageName
1516 + " restore version [" + metaInfo.versionCode
1517 + "] is compatible with installed version ["
1518 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001519
Christopher Tate5e1ab332009-09-01 20:32:49 -07001520 // Now perform the actual restore: first clear the app's data
1521 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001522 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001523
1524 // Then set up and bind the agent (with a restricted Application object
1525 // unless the application says otherwise)
1526 boolean useRealApp = (packageInfo.applicationInfo.flags
1527 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1528 if (DEBUG && useRealApp) {
1529 Log.v(TAG, "agent requires real Application subclass for restore");
1530 }
Dan Egnorefe52642009-06-24 00:16:33 -07001531 IBackupAgent agent = bindToAgentSynchronous(
1532 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001533 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1534 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001535 if (agent == null) {
1536 Log.w(TAG, "Can't find backup agent for " + packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001537 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName,
1538 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001539 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001540 }
1541
Christopher Tate5e1ab332009-09-01 20:32:49 -07001542 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001543 try {
1544 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001545 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001546 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001547 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001548 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001549
1550 // The agent was probably running with a stub Application object,
1551 // which isn't a valid run mode for the main app logic. Shut
1552 // down the app so that next time it's launched, it gets the
1553 // usual full initialization.
1554 if ((packageInfo.applicationInfo.flags
1555 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1556 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1557 + packageInfo.applicationInfo.processName);
1558 mActivityManager.killApplicationProcess(
1559 packageInfo.applicationInfo.processName,
1560 packageInfo.applicationInfo.uid);
1561 }
Dan Egnorefe52642009-06-24 00:16:33 -07001562 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001563 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001564
1565 // if we get this far, report success to the observer
1566 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001567 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1568 EventLog.writeEvent(RESTORE_SUCCESS_EVENT, count, millis);
1569 } catch (Exception e) {
1570 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001571 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001572 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1573
Dan Egnorefe52642009-06-24 00:16:33 -07001574 try {
1575 mTransport.finishRestore();
1576 } catch (RemoteException e) {
1577 Log.e(TAG, "Error finishing restore", e);
1578 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001579
1580 if (mObserver != null) {
1581 try {
1582 mObserver.restoreFinished(error);
1583 } catch (RemoteException e) {
1584 Log.d(TAG, "Restore observer died at restoreFinished");
1585 }
1586 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001587
1588 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001589 synchronized (mQueueLock) {
1590 mBackupOrRestoreInProgress = false;
1591 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001592 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001593 }
1594 }
1595
Dan Egnorefe52642009-06-24 00:16:33 -07001596 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1597 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001598 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001599 final String packageName = app.packageName;
1600
Dan Egnorbb9001c2009-07-27 12:20:13 -07001601 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001602
Christopher Tate0749dcd2009-08-13 15:13:03 -07001603 // Don't restore to unprivileged packages
1604 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1605 packageName) != PackageManager.PERMISSION_GRANTED) {
1606 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1607 }
1608
Christopher Tatec7b31e32009-06-10 15:49:30 -07001609 // !!! TODO: get the dirs from the transport
1610 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001611 File newStateName = new File(mStateDir, packageName + ".new");
1612 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001613
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614 ParcelFileDescriptor backupData = null;
1615 ParcelFileDescriptor newState = null;
1616
1617 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001618 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001619 backupData = ParcelFileDescriptor.open(backupDataName,
1620 ParcelFileDescriptor.MODE_READ_WRITE |
1621 ParcelFileDescriptor.MODE_CREATE |
1622 ParcelFileDescriptor.MODE_TRUNCATE);
1623
Dan Egnor01445162009-09-21 17:04:05 -07001624 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 Log.e(TAG, "Error getting restore data for " + packageName);
1626 EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
1627 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001628 }
1629
1630 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001631 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001632 backupData = ParcelFileDescriptor.open(backupDataName,
1633 ParcelFileDescriptor.MODE_READ_ONLY);
1634
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 newState = ParcelFileDescriptor.open(newStateName,
1636 ParcelFileDescriptor.MODE_READ_WRITE |
1637 ParcelFileDescriptor.MODE_CREATE |
1638 ParcelFileDescriptor.MODE_TRUNCATE);
1639
1640 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001641
1642 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001643 //
1644 // !!! TODO: the restored data should be migrated on the server
1645 // side into the current dataset. In that case the new state file
1646 // we just created would reflect the data already extant in the
1647 // backend, so there'd be nothing more to do. Until that happens,
1648 // however, we need to make sure that we record the data to the
1649 // current backend dataset. (Yes, this means shipping the data over
1650 // the wire in both directions. That's bad, but consistency comes
1651 // first, then efficiency.) Once we introduce server-side data
1652 // migration to the newly-restored device's dataset, we will change
1653 // the following from a discard of the newly-written state to the
1654 // "correct" operation of renaming into the canonical state blob.
1655 newStateName.delete(); // TODO: remove; see above comment
1656 //newStateName.renameTo(savedStateName); // TODO: replace with this
1657
Dan Egnorbb9001c2009-07-27 12:20:13 -07001658 int size = (int) backupDataName.length();
1659 EventLog.writeEvent(RESTORE_PACKAGE_EVENT, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001660 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001661 Log.e(TAG, "Error restoring data for " + packageName, e);
1662 EventLog.writeEvent(RESTORE_AGENT_FAILURE_EVENT, packageName, e.toString());
1663
Christopher Tate96733042009-07-20 14:49:13 -07001664 // If the agent fails restore, it might have put the app's data
1665 // into an incoherent state. For consistency we wipe its data
1666 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001667 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001668 } finally {
1669 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001670 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1671 try { if (newState != null) newState.close(); } catch (IOException e) {}
1672 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001673 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001674 }
1675 }
1676
Christopher Tateee0e78a2009-07-02 11:17:03 -07001677 class PerformClearThread extends Thread {
1678 IBackupTransport mTransport;
1679 PackageInfo mPackage;
1680
1681 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1682 mTransport = transport;
1683 mPackage = packageInfo;
1684 }
1685
1686 @Override
1687 public void run() {
1688 try {
1689 // Clear the on-device backup state to ensure a full backup next time
1690 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1691 File stateFile = new File(stateDir, mPackage.packageName);
1692 stateFile.delete();
1693
1694 // Tell the transport to remove all the persistent storage for the app
Dan Egnor83861e72009-09-17 16:17:55 -07001695 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001696 mTransport.clearBackupData(mPackage);
1697 } catch (RemoteException e) {
1698 // can't happen; the transport is local
1699 } finally {
1700 try {
Dan Egnor83861e72009-09-17 16:17:55 -07001701 // STOPSHIP TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001702 mTransport.finishBackup();
1703 } catch (RemoteException e) {
1704 // can't happen; the transport is local
1705 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001706
1707 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001708 synchronized (mQueueLock) {
1709 mBackupOrRestoreInProgress = false;
1710 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001711 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001712 }
1713 }
1714 }
1715
Christopher Tate4cc86e12009-09-21 19:36:51 -07001716 class PerformInitializeThread extends Thread {
1717 HashSet<String> mQueue;
1718
1719 PerformInitializeThread(HashSet<String> transportNames) {
1720 mQueue = transportNames;
1721 }
1722
1723 @Override
1724 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001725 try {
1726 for (String transportName : mQueue) {
1727 IBackupTransport transport = getTransport(transportName);
1728 if (transport == null) {
1729 Log.e(TAG, "Requested init for " + transportName + " but not found");
1730 continue;
1731 }
1732
Dan Egnor726247c2009-09-29 19:12:31 -07001733 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
1734 EventLog.writeEvent(BACKUP_START_EVENT, transport.transportDirName());
1735 long startRealtime = SystemClock.elapsedRealtime();
1736 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001737
Christopher Tate4cc86e12009-09-21 19:36:51 -07001738 if (status == BackupConstants.TRANSPORT_OK) {
1739 status = transport.finishBackup();
1740 }
1741
1742 // Okay, the wipe really happened. Clean up our local bookkeeping.
1743 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001744 Log.i(TAG, "Device init successful");
1745 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
1746 EventLog.writeEvent(BACKUP_INITIALIZE_EVENT);
1747 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
1748 EventLog.writeEvent(BACKUP_SUCCESS_EVENT, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001749 synchronized (mQueueLock) {
1750 recordInitPendingLocked(false, transportName);
1751 }
Dan Egnor726247c2009-09-29 19:12:31 -07001752 } else {
1753 // If this didn't work, requeue this one and try again
1754 // after a suitable interval
1755 Log.e(TAG, "Transport error in initializeDevice()");
1756 EventLog.writeEvent(BACKUP_TRANSPORT_FAILURE_EVENT, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001757 synchronized (mQueueLock) {
1758 recordInitPendingLocked(true, transportName);
1759 }
1760 // do this via another alarm to make sure of the wakelock states
1761 long delay = transport.requestBackupTime();
1762 if (DEBUG) Log.w(TAG, "init failed on "
1763 + transportName + " resched in " + delay);
1764 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1765 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001766 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001767 }
1768 } catch (RemoteException e) {
1769 // can't happen; the transports are local
1770 } catch (Exception e) {
1771 Log.e(TAG, "Unexpected error performing init", e);
1772 } finally {
1773 // Done; indicate that we're finished and release the wakelock
1774 synchronized (mQueueLock) {
1775 mInitInProgress = false;
1776 }
1777 mWakelock.release();
1778 }
1779 }
1780 }
1781
Christopher Tatedf01dea2009-06-09 20:45:02 -07001782
Christopher Tate487529a2009-04-29 14:03:25 -07001783 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001784
Christopher Tatea8bf8152009-04-30 11:36:21 -07001785 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001786 // Record that we need a backup pass for the caller. Since multiple callers
1787 // may share a uid, we need to note all candidates within that uid and schedule
1788 // a backup pass for each of them.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001789 EventLog.writeEvent(BACKUP_DATA_CHANGED_EVENT, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001790
Christopher Tate63d27002009-06-16 17:16:42 -07001791 // If the caller does not hold the BACKUP permission, it can only request a
1792 // backup of its own data.
1793 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001794 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001795 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1796 targets = mBackupParticipants.get(Binder.getCallingUid());
1797 } else {
1798 // a caller with full permission can ask to back up any participating app
1799 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001800 targets = new HashSet<ApplicationInfo>();
1801 int N = mBackupParticipants.size();
1802 for (int i = 0; i < N; i++) {
1803 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1804 if (s != null) {
1805 targets.addAll(s);
1806 }
1807 }
1808 }
Christopher Tate487529a2009-04-29 14:03:25 -07001809 if (targets != null) {
1810 synchronized (mQueueLock) {
1811 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001812 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001813 // validate the caller-supplied package name against the known set of
1814 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001815 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001816 // Add the caller to the set of pending backups. If there is
1817 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001818 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001819 if (mPendingBackups.put(app, req) == null) {
1820 // Journal this request in case of crash. The put()
1821 // operation returned null when this package was not already
1822 // in the set; we want to avoid touching the disk redundantly.
1823 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001824
Christopher Tate22b60d82009-07-07 16:36:02 -07001825 if (DEBUG) {
1826 int numKeys = mPendingBackups.size();
1827 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1828 for (BackupRequest b : mPendingBackups.values()) {
1829 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1830 }
1831 }
1832 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001833 }
1834 }
Christopher Tate487529a2009-04-29 14:03:25 -07001835 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001836 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001837 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1838 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001839 }
1840 }
Christopher Tate46758122009-05-06 11:22:00 -07001841
Christopher Tatecde87f42009-06-12 12:55:53 -07001842 private void writeToJournalLocked(String str) {
1843 if (mJournalStream != null) {
1844 try {
1845 mJournalStream.writeUTF(str);
1846 } catch (IOException e) {
1847 Log.e(TAG, "Error writing to backup journal");
1848 mJournalStream = null;
1849 mJournal = null;
1850 }
1851 }
1852 }
1853
Christopher Tateee0e78a2009-07-02 11:17:03 -07001854 // Clear the given package's backup data from the current transport
1855 public void clearBackupData(String packageName) {
1856 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1857 PackageInfo info;
1858 try {
1859 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1860 } catch (NameNotFoundException e) {
1861 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1862 return;
1863 }
1864
1865 // If the caller does not hold the BACKUP permission, it can only request a
1866 // wipe of its own backed-up data.
1867 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001868 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001869 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1870 apps = mBackupParticipants.get(Binder.getCallingUid());
1871 } else {
1872 // a caller with full permission can ask to back up any participating app
1873 // !!! TODO: allow data-clear of ANY app?
1874 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1875 apps = new HashSet<ApplicationInfo>();
1876 int N = mBackupParticipants.size();
1877 for (int i = 0; i < N; i++) {
1878 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1879 if (s != null) {
1880 apps.addAll(s);
1881 }
1882 }
1883 }
1884
1885 // now find the given package in the set of candidate apps
1886 for (ApplicationInfo app : apps) {
1887 if (app.packageName.equals(packageName)) {
1888 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1889 // found it; fire off the clear request
1890 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001891 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001892 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001893 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1894 new ClearParams(getTransport(mCurrentTransport), info));
1895 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001896 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001897 }
1898 break;
1899 }
1900 }
1901 }
1902
Christopher Tateace7f092009-06-15 18:07:25 -07001903 // Run a backup pass immediately for any applications that have declared
1904 // that they have pending updates.
1905 public void backupNow() throws RemoteException {
Joe Onorato5933a492009-07-23 18:24:08 -04001906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001907
Christopher Tateace7f092009-06-15 18:07:25 -07001908 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001909 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001910 // Because the alarms we are using can jitter, and we want an *immediate*
1911 // backup pass to happen, we restart the timer beginning with "next time,"
1912 // then manually fire the backup trigger intent ourselves.
1913 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001914 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001915 mRunBackupIntent.send();
1916 } catch (PendingIntent.CanceledException e) {
1917 // should never happen
1918 Log.e(TAG, "run-backup intent cancelled!");
1919 }
Christopher Tate46758122009-05-06 11:22:00 -07001920 }
1921 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001922
Christopher Tate8031a3d2009-07-06 16:36:05 -07001923 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001924 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1926 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001927
Christopher Tate4cc86e12009-09-21 19:36:51 -07001928 Log.i(TAG, "Backup enabled => " + enable);
1929
Christopher Tate6ef58a12009-06-29 14:56:28 -07001930 boolean wasEnabled = mEnabled;
1931 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001932 Settings.Secure.putInt(mContext.getContentResolver(),
1933 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001934 mEnabled = enable;
1935 }
1936
Christopher Tate49401dd2009-07-01 12:34:29 -07001937 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001938 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001939 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001940 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001941 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001942 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001943 if (DEBUG) Log.i(TAG, "Opting out of backup");
1944
Christopher Tateb6787f22009-07-02 17:40:45 -07001945 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001946
1947 // This also constitutes an opt-out, so we wipe any data for
1948 // this device from the backend. We start that process with
1949 // an alarm in order to guarantee wakelock states.
1950 if (wasEnabled && mProvisioned) {
1951 // NOTE: we currently flush every registered transport, not just
1952 // the currently-active one.
1953 HashSet<String> allTransports;
1954 synchronized (mTransports) {
1955 allTransports = new HashSet<String>(mTransports.keySet());
1956 }
1957 // build the set of transports for which we are posting an init
1958 for (String transport : allTransports) {
1959 recordInitPendingLocked(true, transport);
1960 }
1961 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1962 mRunInitIntent);
1963 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001964 }
1965 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001966 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001967
Christopher Tate8031a3d2009-07-06 16:36:05 -07001968 // Mark the backup service as having been provisioned
1969 public void setBackupProvisioned(boolean available) {
1970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1971 "setBackupProvisioned");
1972
1973 boolean wasProvisioned = mProvisioned;
1974 synchronized (this) {
1975 Settings.Secure.putInt(mContext.getContentResolver(),
1976 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1977 mProvisioned = available;
1978 }
1979
1980 synchronized (mQueueLock) {
1981 if (available && !wasProvisioned && mEnabled) {
1982 // we're now good to go, so start the backup alarms
1983 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1984 } else if (!available) {
1985 // No longer enabled, so stop running backups
1986 Log.w(TAG, "Backup service no longer provisioned");
1987 mAlarmManager.cancel(mRunBackupIntent);
1988 }
1989 }
1990 }
1991
1992 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1993 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1994 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1995 BACKUP_INTERVAL, mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001996 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001997 }
1998
Christopher Tate6ef58a12009-06-29 14:56:28 -07001999 // Report whether the backup mechanism is currently enabled
2000 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002002 return mEnabled; // no need to synchronize just to read it
2003 }
2004
Christopher Tate91717492009-06-26 21:07:13 -07002005 // Report the name of the currently active transport
2006 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002007 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002008 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002009 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002010 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002011 }
2012
Christopher Tate91717492009-06-26 21:07:13 -07002013 // Report all known, available backup transports
2014 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002015 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002016
Christopher Tate91717492009-06-26 21:07:13 -07002017 String[] list = null;
2018 ArrayList<String> known = new ArrayList<String>();
2019 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2020 if (entry.getValue() != null) {
2021 known.add(entry.getKey());
2022 }
2023 }
2024
2025 if (known.size() > 0) {
2026 list = new String[known.size()];
2027 known.toArray(list);
2028 }
2029 return list;
2030 }
2031
2032 // Select which transport to use for the next backup operation. If the given
2033 // name is not one of the available transports, no action is taken and the method
2034 // returns null.
2035 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002037
2038 synchronized (mTransports) {
2039 String prevTransport = null;
2040 if (mTransports.get(transport) != null) {
2041 prevTransport = mCurrentTransport;
2042 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002043 Settings.Secure.putString(mContext.getContentResolver(),
2044 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002045 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2046 + " returning " + prevTransport);
2047 } else {
2048 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2049 }
2050 return prevTransport;
2051 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002052 }
2053
2054 // Callback: a requested backup agent has been instantiated. This should only
2055 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002056 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002057 synchronized(mAgentConnectLock) {
2058 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2059 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2060 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2061 mConnectedAgent = agent;
2062 mConnecting = false;
2063 } else {
2064 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2065 + " claiming agent connected");
2066 }
2067 mAgentConnectLock.notifyAll();
2068 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002069 }
2070
2071 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2072 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002073 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002074 public void agentDisconnected(String packageName) {
2075 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002076 synchronized(mAgentConnectLock) {
2077 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2078 mConnectedAgent = null;
2079 mConnecting = false;
2080 } else {
2081 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2082 + " claiming agent disconnected");
2083 }
2084 mAgentConnectLock.notifyAll();
2085 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002086 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002087
Christopher Tate8c850b72009-06-07 19:33:20 -07002088 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002089 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002091
2092 synchronized(this) {
2093 if (mActiveRestoreSession != null) {
2094 Log.d(TAG, "Restore session requested but one already active");
2095 return null;
2096 }
Christopher Tate91717492009-06-26 21:07:13 -07002097 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002098 }
2099 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002100 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002101
Christopher Tate9b3905c2009-06-08 15:24:01 -07002102 // ----- Restore session -----
2103
2104 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002105 private static final String TAG = "RestoreSession";
2106
Christopher Tate9b3905c2009-06-08 15:24:01 -07002107 private IBackupTransport mRestoreTransport = null;
2108 RestoreSet[] mRestoreSets = null;
2109
Christopher Tate91717492009-06-26 21:07:13 -07002110 RestoreSession(String transport) {
2111 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002112 }
2113
2114 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002115 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002117 "getAvailableRestoreSets");
2118
Christopher Tatef68eb502009-06-16 11:02:01 -07002119 try {
Christopher Tate43383042009-07-13 15:17:13 -07002120 if (mRestoreTransport == null) {
2121 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002122 return null;
2123 }
2124 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002125 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002126 if (mRestoreSets == null) EventLog.writeEvent(RESTORE_TRANSPORT_FAILURE_EVENT);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002127 }
2128 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002129 } catch (Exception e) {
2130 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2131 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002132 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002133 }
2134
Dan Egnor0084da52009-07-29 12:57:16 -07002135 public synchronized int performRestore(long token, IRestoreObserver observer) {
2136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2137 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002138
Christopher Tatef2c321a2009-08-10 15:43:36 -07002139 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2140 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002141
Dan Egnor0084da52009-07-29 12:57:16 -07002142 if (mRestoreTransport == null || mRestoreSets == null) {
2143 Log.e(TAG, "Ignoring performRestore() with no restore set");
2144 return -1;
2145 }
2146
Christopher Tate21ab6a52009-09-24 18:01:46 -07002147 synchronized (mQueueLock) {
2148 if (mBackupOrRestoreInProgress) {
2149 Log.e(TAG, "Backup pass in progress, restore aborted");
2150 return -1;
2151 }
2152
2153 for (int i = 0; i < mRestoreSets.length; i++) {
2154 if (token == mRestoreSets[i].token) {
2155 long oldId = Binder.clearCallingIdentity();
2156 // Suppress backups until the restore operation is finished
2157 mBackupOrRestoreInProgress = true;
2158 mWakelock.acquire();
2159 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2160 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2161 mBackupHandler.sendMessage(msg);
2162 Binder.restoreCallingIdentity(oldId);
2163 return 0;
2164 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002165 }
2166 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002167
2168 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002169 return -1;
2170 }
2171
Dan Egnor0084da52009-07-29 12:57:16 -07002172 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002173 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002174 "endRestoreSession");
2175
Dan Egnor0084da52009-07-29 12:57:16 -07002176 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002177
Dan Egnor0084da52009-07-29 12:57:16 -07002178 synchronized (this) {
2179 try {
2180 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2181 } catch (Exception e) {
2182 Log.e(TAG, "Error in finishRestore", e);
2183 } finally {
2184 mRestoreTransport = null;
2185 }
2186 }
2187
2188 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002189 if (BackupManagerService.this.mActiveRestoreSession == this) {
2190 BackupManagerService.this.mActiveRestoreSession = null;
2191 } else {
2192 Log.e(TAG, "ending non-current restore session");
2193 }
2194 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002195 }
2196 }
2197
Christopher Tate043dadc2009-06-02 16:11:00 -07002198
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002199 @Override
2200 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2201 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002202 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002203 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2204 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2205 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2206 + (!mInitInProgress ? "not " : "") + "initializing");
2207 pw.println("Last backup pass: " + mLastBackupPass
2208 + " (now = " + System.currentTimeMillis() + ')');
2209 pw.println(" next scheduled: " + mNextBackupPass);
2210
Christopher Tate91717492009-06-26 21:07:13 -07002211 pw.println("Available transports:");
2212 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002213 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
2214 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07002215 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002216
2217 pw.println("Pending init: " + mPendingInits.size());
2218 for (String s : mPendingInits) {
2219 pw.println(" " + s);
2220 }
2221
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002222 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002223 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002224 for (int i=0; i<N; i++) {
2225 int uid = mBackupParticipants.keyAt(i);
2226 pw.print(" uid: ");
2227 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002228 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2229 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002230 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002231 }
2232 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002233
Christopher Tate73e02522009-07-15 14:18:26 -07002234 pw.println("Ever backed up: " + mEverStoredApps.size());
2235 for (String pkg : mEverStoredApps) {
2236 pw.println(" " + pkg);
2237 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002238
2239 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002240 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002241 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002242 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002243 }
2244 }
Christopher Tate487529a2009-04-29 14:03:25 -07002245}