blob: fb0ffb09c215e4fa63a739b905ea380ce6ded0fd [file] [log] [blame]
Kenny Root15a4d2f2010-03-11 18:20:12 -08001/*
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
Christopher Tate9bbc21a2009-06-10 20:23:25 -070017package com.android.internal.backup;
18
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupDataInput;
20import android.app.backup.BackupDataOutput;
Christopher Tate74318c92014-05-15 19:03:44 -070021import android.app.backup.BackupTransport;
Christopher Tate6a49dd02014-06-16 18:49:25 -070022import android.app.backup.RestoreDescription;
Christopher Tate45281862010-03-05 15:46:30 -080023import android.app.backup.RestoreSet;
Christopher Tatecefba582013-11-14 18:10:35 -080024import android.content.ComponentName;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070025import android.content.Context;
Chris Tatea8ddef32010-11-10 11:53:26 -080026import android.content.Intent;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070027import android.content.pm.PackageInfo;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070028import android.os.Environment;
29import android.os.ParcelFileDescriptor;
rpcraigebab0ae2012-12-04 09:37:23 -050030import android.os.SELinux;
Elliott Hughesf97c6332014-04-28 16:38:43 -070031import android.system.ErrnoException;
32import android.system.Os;
33import android.system.StructStat;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070034import android.util.Log;
35
Brian Carlstrom4140fae2011-01-24 16:17:43 -080036import com.android.org.bouncycastle.util.encoders.Base64;
Christopher Tatee9190a22009-06-17 17:52:05 -070037
Christopher Tate824392b2014-11-14 18:27:36 -080038import libcore.io.IoUtils;
39
Christopher Tate9ff53a72014-06-03 17:20:07 -070040import java.io.BufferedOutputStream;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070041import java.io.File;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070042import java.io.FileInputStream;
Christopher Tate9ff53a72014-06-03 17:20:07 -070043import java.io.FileNotFoundException;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070044import java.io.FileOutputStream;
45import java.io.IOException;
Christopher Tateadfe8b82014-02-04 16:23:32 -080046import java.util.ArrayList;
47import java.util.Collections;
Christopher Tate9ff53a72014-06-03 17:20:07 -070048import java.util.HashSet;
Elliott Hughesf97c6332014-04-28 16:38:43 -070049import static android.system.OsConstants.*;
Christopher Tateb048c332014-02-21 12:50:21 -080050
Christopher Tate9bbc21a2009-06-10 20:23:25 -070051/**
52 * Backup transport for stashing stuff into a known location on disk, and
53 * later restoring from there. For testing only.
54 */
55
Christopher Tate74318c92014-05-15 19:03:44 -070056public class LocalTransport extends BackupTransport {
Christopher Tate9bbc21a2009-06-10 20:23:25 -070057 private static final String TAG = "LocalTransport";
Ed Heyla50cd8d2014-07-14 23:42:04 -070058 private static final boolean DEBUG = false;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070059
Christopher Tate5cb400b2009-06-25 16:03:14 -070060 private static final String TRANSPORT_DIR_NAME
61 = "com.android.internal.backup.LocalTransport";
62
Chris Tatea8ddef32010-11-10 11:53:26 -080063 private static final String TRANSPORT_DESTINATION_STRING
64 = "Backing up to debug-only private cache";
65
Christopher Tate96794102014-07-27 20:21:55 -070066 private static final String TRANSPORT_DATA_MANAGEMENT_LABEL
67 = "";
68
Christopher Tate6a49dd02014-06-16 18:49:25 -070069 private static final String INCREMENTAL_DIR = "_delta";
70 private static final String FULL_DATA_DIR = "_full";
71
Christopher Tateadfe8b82014-02-04 16:23:32 -080072 // The currently-active restore set always has the same (nonzero!) token
73 private static final long CURRENT_SET_TOKEN = 1;
Christopher Tate50c6df02010-01-29 12:48:20 -080074
Christopher Tate9bbc21a2009-06-10 20:23:25 -070075 private Context mContext;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070076 private File mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup");
Christopher Tateadfe8b82014-02-04 16:23:32 -080077 private File mCurrentSetDir = new File(mDataDir, Long.toString(CURRENT_SET_TOKEN));
Christopher Tate6a49dd02014-06-16 18:49:25 -070078 private File mCurrentSetIncrementalDir = new File(mCurrentSetDir, INCREMENTAL_DIR);
79 private File mCurrentSetFullDir = new File(mCurrentSetDir, FULL_DATA_DIR);
Christopher Tateadfe8b82014-02-04 16:23:32 -080080
Dan Egnorefe52642009-06-24 00:16:33 -070081 private PackageInfo[] mRestorePackages = null;
82 private int mRestorePackage = -1; // Index into mRestorePackages
Christopher Tate6a49dd02014-06-16 18:49:25 -070083 private int mRestoreType;
84 private File mRestoreSetDir;
85 private File mRestoreSetIncrementalDir;
86 private File mRestoreSetFullDir;
Christopher Tateadfe8b82014-02-04 16:23:32 -080087 private long mRestoreToken;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070088
Christopher Tate9ff53a72014-06-03 17:20:07 -070089 // Additional bookkeeping for full backup
90 private String mFullTargetPackage;
91 private ParcelFileDescriptor mSocket;
92 private FileInputStream mSocketInputStream;
93 private BufferedOutputStream mFullBackupOutputStream;
94 private byte[] mFullBackupBuffer;
95
96 private File mFullRestoreSetDir;
97 private HashSet<String> mFullRestorePackages;
Christopher Tate5a009f92014-06-19 14:53:18 -070098 private FileInputStream mCurFullRestoreStream;
99 private FileOutputStream mFullRestoreSocketStream;
100 private byte[] mFullRestoreBuffer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700101
102 public LocalTransport(Context context) {
103 mContext = context;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800104 mCurrentSetDir.mkdirs();
Christopher Tate9ff53a72014-06-03 17:20:07 -0700105 mCurrentSetFullDir.mkdir();
106 mCurrentSetIncrementalDir.mkdir();
Christopher Tateadfe8b82014-02-04 16:23:32 -0800107 if (!SELinux.restorecon(mCurrentSetDir)) {
108 Log.e(TAG, "SELinux restorecon failed for " + mCurrentSetDir);
rpcraigebab0ae2012-12-04 09:37:23 -0500109 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700110 }
111
Christopher Tate5a009f92014-06-19 14:53:18 -0700112 @Override
Christopher Tatecefba582013-11-14 18:10:35 -0800113 public String name() {
114 return new ComponentName(mContext, this.getClass()).flattenToShortString();
115 }
116
Christopher Tate5a009f92014-06-19 14:53:18 -0700117 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800118 public Intent configurationIntent() {
119 // The local transport is not user-configurable
120 return null;
121 }
122
Christopher Tate5a009f92014-06-19 14:53:18 -0700123 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800124 public String currentDestinationString() {
125 return TRANSPORT_DESTINATION_STRING;
126 }
Christopher Tate5cb400b2009-06-25 16:03:14 -0700127
Christopher Tate96794102014-07-27 20:21:55 -0700128 public Intent dataManagementIntent() {
129 // The local transport does not present a data-management UI
130 // TODO: consider adding simple UI to wipe the archives entirely,
131 // for cleaning up the cache partition.
132 return null;
133 }
134
135 public String dataManagementLabel() {
136 return TRANSPORT_DATA_MANAGEMENT_LABEL;
137 }
138
Christopher Tate5a009f92014-06-19 14:53:18 -0700139 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700140 public String transportDirName() {
Christopher Tate5cb400b2009-06-25 16:03:14 -0700141 return TRANSPORT_DIR_NAME;
142 }
143
Christopher Tate5a009f92014-06-19 14:53:18 -0700144 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700145 public long requestBackupTime() {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700146 // any time is a good time for local backup
147 return 0;
148 }
149
Christopher Tate5a009f92014-06-19 14:53:18 -0700150 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700151 public int initializeDevice() {
152 if (DEBUG) Log.v(TAG, "wiping all data");
Christopher Tateadfe8b82014-02-04 16:23:32 -0800153 deleteContents(mCurrentSetDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700154 return TRANSPORT_OK;
Dan Egnor01445162009-09-21 17:04:05 -0700155 }
156
Christopher Tate5a009f92014-06-19 14:53:18 -0700157 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700158 public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) {
Christopher Tateb048c332014-02-21 12:50:21 -0800159 if (DEBUG) {
160 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700161 StructStat ss = Os.fstat(data.getFileDescriptor());
Christopher Tateb048c332014-02-21 12:50:21 -0800162 Log.v(TAG, "performBackup() pkg=" + packageInfo.packageName
163 + " size=" + ss.st_size);
164 } catch (ErrnoException e) {
165 Log.w(TAG, "Unable to stat input file in performBackup() on "
166 + packageInfo.packageName);
167 }
168 }
Christopher Tate2fdd4282009-06-12 15:20:04 -0700169
Christopher Tate9ff53a72014-06-03 17:20:07 -0700170 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate2fdd4282009-06-12 15:20:04 -0700171 packageDir.mkdirs();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700172
Christopher Tate2fdd4282009-06-12 15:20:04 -0700173 // Each 'record' in the restore set is kept in its own file, named by
174 // the record key. Wind through the data file, extracting individual
175 // record operations and building a set of all the updates to apply
176 // in this update.
177 BackupDataInput changeSet = new BackupDataInput(data.getFileDescriptor());
178 try {
179 int bufSize = 512;
180 byte[] buf = new byte[bufSize];
181 while (changeSet.readNextHeader()) {
182 String key = changeSet.getKey();
Joe Onorato5d605dc2009-06-18 18:23:43 -0700183 String base64Key = new String(Base64.encode(key.getBytes()));
184 File entityFile = new File(packageDir, base64Key);
185
Christopher Tate2fdd4282009-06-12 15:20:04 -0700186 int dataSize = changeSet.getDataSize();
Christopher Tatee9190a22009-06-17 17:52:05 -0700187
Christopher Tatee9190a22009-06-17 17:52:05 -0700188 if (DEBUG) Log.v(TAG, "Got change set key=" + key + " size=" + dataSize
189 + " key64=" + base64Key);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700190
Joe Onorato5d605dc2009-06-18 18:23:43 -0700191 if (dataSize >= 0) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700192 if (entityFile.exists()) {
193 entityFile.delete();
194 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700195 FileOutputStream entity = new FileOutputStream(entityFile);
196
197 if (dataSize > bufSize) {
198 bufSize = dataSize;
199 buf = new byte[bufSize];
200 }
201 changeSet.readEntityData(buf, 0, dataSize);
Christopher Tateb048c332014-02-21 12:50:21 -0800202 if (DEBUG) {
203 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700204 long cur = Os.lseek(data.getFileDescriptor(), 0, SEEK_CUR);
Christopher Tateb048c332014-02-21 12:50:21 -0800205 Log.v(TAG, " read entity data; new pos=" + cur);
206 }
207 catch (ErrnoException e) {
208 Log.w(TAG, "Unable to stat input file in performBackup() on "
209 + packageInfo.packageName);
210 }
211 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700212
213 try {
214 entity.write(buf, 0, dataSize);
215 } catch (IOException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700216 Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath());
Christopher Tate5a009f92014-06-19 14:53:18 -0700217 return TRANSPORT_ERROR;
Joe Onorato5d605dc2009-06-18 18:23:43 -0700218 } finally {
219 entity.close();
220 }
221 } else {
222 entityFile.delete();
Christopher Tate2fdd4282009-06-12 15:20:04 -0700223 }
224 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700225 return TRANSPORT_OK;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700226 } catch (IOException e) {
227 // oops, something went wrong. abort the operation and return error.
Dan Egnorefe52642009-06-24 00:16:33 -0700228 Log.v(TAG, "Exception reading backup input:", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700229 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700230 }
Dan Egnorefe52642009-06-24 00:16:33 -0700231 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700232
Christopher Tate25a747f2009-09-20 12:43:58 -0700233 // Deletes the contents but not the given directory
234 private void deleteContents(File dirname) {
235 File[] contents = dirname.listFiles();
236 if (contents != null) {
237 for (File f : contents) {
238 if (f.isDirectory()) {
239 // delete the directory's contents then fall through
240 // and delete the directory itself.
241 deleteContents(f);
242 }
243 f.delete();
244 }
245 }
246 }
247
Christopher Tate5a009f92014-06-19 14:53:18 -0700248 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700249 public int clearBackupData(PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700250 if (DEBUG) Log.v(TAG, "clearBackupData() pkg=" + packageInfo.packageName);
251
Christopher Tate9ff53a72014-06-03 17:20:07 -0700252 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate0abf6a02012-03-23 17:45:15 -0700253 final File[] fileset = packageDir.listFiles();
254 if (fileset != null) {
255 for (File f : fileset) {
256 f.delete();
257 }
258 packageDir.delete();
Christopher Tateee0e78a2009-07-02 11:17:03 -0700259 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700260
261 packageDir = new File(mCurrentSetFullDir, packageInfo.packageName);
262 final File[] tarballs = packageDir.listFiles();
263 if (tarballs != null) {
264 for (File f : tarballs) {
265 f.delete();
266 }
267 packageDir.delete();
268 }
269
Christopher Tate5a009f92014-06-19 14:53:18 -0700270 return TRANSPORT_OK;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700271 }
272
Christopher Tate5a009f92014-06-19 14:53:18 -0700273 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700274 public int finishBackup() {
Christopher Tatee0792642014-08-07 14:19:50 -0700275 if (DEBUG) Log.v(TAG, "finishBackup() of " + mFullTargetPackage);
276 return tearDownFullBackup();
277 }
278
279 // ------------------------------------------------------------------------------------
280 // Full backup handling
281
282 private int tearDownFullBackup() {
Christopher Tate9ff53a72014-06-03 17:20:07 -0700283 if (mSocket != null) {
Christopher Tate9ff53a72014-06-03 17:20:07 -0700284 try {
285 mFullBackupOutputStream.flush();
286 mFullBackupOutputStream.close();
287 mSocketInputStream = null;
288 mFullTargetPackage = null;
289 mSocket.close();
290 } catch (IOException e) {
Christopher Tate89101f72014-07-17 19:09:00 -0700291 if (DEBUG) {
Christopher Tatee0792642014-08-07 14:19:50 -0700292 Log.w(TAG, "Exception caught in tearDownFullBackup()", e);
Christopher Tate89101f72014-07-17 19:09:00 -0700293 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700294 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700295 } finally {
296 mSocket = null;
297 }
298 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700299 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700300 }
301
Christopher Tatee0792642014-08-07 14:19:50 -0700302 private File tarballFile(String pkgName) {
303 return new File(mCurrentSetFullDir, pkgName);
304 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700305
306 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700307 public long requestFullBackupTime() {
308 return 0;
309 }
310
Christopher Tate5a009f92014-06-19 14:53:18 -0700311 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700312 public int performFullBackup(PackageInfo targetPackage, ParcelFileDescriptor socket) {
313 if (mSocket != null) {
314 Log.e(TAG, "Attempt to initiate full backup while one is in progress");
Christopher Tate5a009f92014-06-19 14:53:18 -0700315 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700316 }
317
318 if (DEBUG) {
319 Log.i(TAG, "performFullBackup : " + targetPackage);
320 }
321
322 // We know a priori that we run in the system process, so we need to make
323 // sure to dup() our own copy of the socket fd. Transports which run in
324 // their own processes must not do this.
325 try {
326 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
327 mSocketInputStream = new FileInputStream(mSocket.getFileDescriptor());
328 } catch (IOException e) {
329 Log.e(TAG, "Unable to process socket for full backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700330 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700331 }
332
333 mFullTargetPackage = targetPackage.packageName;
334 FileOutputStream tarstream;
335 try {
Christopher Tatee0792642014-08-07 14:19:50 -0700336 File tarball = tarballFile(mFullTargetPackage);
Christopher Tate9ff53a72014-06-03 17:20:07 -0700337 tarstream = new FileOutputStream(tarball);
338 } catch (FileNotFoundException e) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700339 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700340 }
341 mFullBackupOutputStream = new BufferedOutputStream(tarstream);
342 mFullBackupBuffer = new byte[4096];
343
Christopher Tate5a009f92014-06-19 14:53:18 -0700344 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700345 }
346
Christopher Tate5a009f92014-06-19 14:53:18 -0700347 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700348 public int sendBackupData(int numBytes) {
349 if (mFullBackupBuffer == null) {
350 Log.w(TAG, "Attempted sendBackupData before performFullBackup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700351 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700352 }
353
354 if (numBytes > mFullBackupBuffer.length) {
355 mFullBackupBuffer = new byte[numBytes];
356 }
357 while (numBytes > 0) {
358 try {
359 int nRead = mSocketInputStream.read(mFullBackupBuffer, 0, numBytes);
360 if (nRead < 0) {
361 // Something went wrong if we expect data but saw EOD
362 Log.w(TAG, "Unexpected EOD; failing backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700363 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700364 }
365 mFullBackupOutputStream.write(mFullBackupBuffer, 0, nRead);
366 numBytes -= nRead;
367 } catch (IOException e) {
368 Log.e(TAG, "Error handling backup data for " + mFullTargetPackage);
Christopher Tate5a009f92014-06-19 14:53:18 -0700369 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700370 }
371 }
Christopher Tate77a2d78d2015-03-03 16:19:44 -0800372 if (DEBUG) {
373 Log.v(TAG, " stored " + numBytes + " of data");
374 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700375 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700376 }
377
Christopher Tatee0792642014-08-07 14:19:50 -0700378 // For now we can't roll back, so just tear everything down.
379 @Override
380 public void cancelFullBackup() {
381 if (DEBUG) {
382 Log.i(TAG, "Canceling full backup of " + mFullTargetPackage);
383 }
384 File archive = tarballFile(mFullTargetPackage);
385 tearDownFullBackup();
386 if (archive.exists()) {
387 archive.delete();
388 }
389 }
390
Christopher Tate9ff53a72014-06-03 17:20:07 -0700391 // ------------------------------------------------------------------------------------
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700392 // Restore handling
Christopher Tate51fea572014-06-23 17:01:06 -0700393 static final long[] POSSIBLE_SETS = { 2, 3, 4, 5, 6, 7, 8, 9 };
Christopher Tate5a009f92014-06-19 14:53:18 -0700394
395 @Override
Christopher Tate74318c92014-05-15 19:03:44 -0700396 public RestoreSet[] getAvailableRestoreSets() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800397 long[] existing = new long[POSSIBLE_SETS.length + 1];
398 int num = 0;
399
Christopher Tate9ff53a72014-06-03 17:20:07 -0700400 // see which possible non-current sets exist...
Christopher Tateadfe8b82014-02-04 16:23:32 -0800401 for (long token : POSSIBLE_SETS) {
402 if ((new File(mDataDir, Long.toString(token))).exists()) {
403 existing[num++] = token;
404 }
405 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700406 // ...and always the currently-active set last
Christopher Tateadfe8b82014-02-04 16:23:32 -0800407 existing[num++] = CURRENT_SET_TOKEN;
408
409 RestoreSet[] available = new RestoreSet[num];
410 for (int i = 0; i < available.length; i++) {
411 available[i] = new RestoreSet("Local disk image", "flash", existing[i]);
412 }
413 return available;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700414 }
415
Christopher Tate5a009f92014-06-19 14:53:18 -0700416 @Override
Christopher Tate50c6df02010-01-29 12:48:20 -0800417 public long getCurrentRestoreSet() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800418 // The current restore set always has the same token
419 return CURRENT_SET_TOKEN;
Christopher Tate50c6df02010-01-29 12:48:20 -0800420 }
421
Christopher Tate5a009f92014-06-19 14:53:18 -0700422 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700423 public int startRestore(long token, PackageInfo[] packages) {
Christopher Tate51fea572014-06-23 17:01:06 -0700424 if (DEBUG) Log.v(TAG, "start restore " + token + " : " + packages.length
425 + " matching packages");
Dan Egnorefe52642009-06-24 00:16:33 -0700426 mRestorePackages = packages;
427 mRestorePackage = -1;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800428 mRestoreToken = token;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700429 mRestoreSetDir = new File(mDataDir, Long.toString(token));
430 mRestoreSetIncrementalDir = new File(mRestoreSetDir, INCREMENTAL_DIR);
431 mRestoreSetFullDir = new File(mRestoreSetDir, FULL_DATA_DIR);
Christopher Tate5a009f92014-06-19 14:53:18 -0700432 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700433 }
434
Christopher Tate6a49dd02014-06-16 18:49:25 -0700435 @Override
436 public RestoreDescription nextRestorePackage() {
Christopher Tate77a2d78d2015-03-03 16:19:44 -0800437 if (DEBUG) {
438 Log.v(TAG, "nextRestorePackage() : mRestorePackage=" + mRestorePackage
439 + " length=" + mRestorePackages.length);
440 }
Dan Egnorefe52642009-06-24 00:16:33 -0700441 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700442
443 boolean found = false;
Dan Egnorefe52642009-06-24 00:16:33 -0700444 while (++mRestorePackage < mRestorePackages.length) {
445 String name = mRestorePackages[mRestorePackage].packageName;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700446
447 // If we have key/value data for this package, deliver that
Christopher Tatea9b91862014-02-25 17:42:21 -0800448 // skip packages where we have a data dir but no actual contents
Christopher Tate6a49dd02014-06-16 18:49:25 -0700449 String[] contents = (new File(mRestoreSetIncrementalDir, name)).list();
Christopher Tatea9b91862014-02-25 17:42:21 -0800450 if (contents != null && contents.length > 0) {
Christopher Tate77a2d78d2015-03-03 16:19:44 -0800451 if (DEBUG) {
452 Log.v(TAG, " nextRestorePackage(TYPE_KEY_VALUE) @ "
453 + mRestorePackage + " = " + name);
454 }
Christopher Tate6a49dd02014-06-16 18:49:25 -0700455 mRestoreType = RestoreDescription.TYPE_KEY_VALUE;
456 found = true;
457 }
458
459 if (!found) {
460 // No key/value data; check for [non-empty] full data
461 File maybeFullData = new File(mRestoreSetFullDir, name);
462 if (maybeFullData.length() > 0) {
Christopher Tate77a2d78d2015-03-03 16:19:44 -0800463 if (DEBUG) {
464 Log.v(TAG, " nextRestorePackage(TYPE_FULL_STREAM) @ "
465 + mRestorePackage + " = " + name);
466 }
Christopher Tate6a49dd02014-06-16 18:49:25 -0700467 mRestoreType = RestoreDescription.TYPE_FULL_STREAM;
Christopher Tate5a009f92014-06-19 14:53:18 -0700468 mCurFullRestoreStream = null; // ensure starting from the ground state
Christopher Tate6a49dd02014-06-16 18:49:25 -0700469 found = true;
470 }
471 }
472
473 if (found) {
474 return new RestoreDescription(name, mRestoreType);
Dan Egnorefe52642009-06-24 00:16:33 -0700475 }
Christopher Tate77a2d78d2015-03-03 16:19:44 -0800476
477 if (DEBUG) {
478 Log.v(TAG, " ... package @ " + mRestorePackage + " = " + name
479 + " has no data; skipping");
480 }
Dan Egnorefe52642009-06-24 00:16:33 -0700481 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700482
Dan Egnorefe52642009-06-24 00:16:33 -0700483 if (DEBUG) Log.v(TAG, " no more packages to restore");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700484 return RestoreDescription.NO_MORE_PACKAGES;
Dan Egnorefe52642009-06-24 00:16:33 -0700485 }
486
Christopher Tate5a009f92014-06-19 14:53:18 -0700487 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700488 public int getRestoreData(ParcelFileDescriptor outFd) {
Dan Egnorefe52642009-06-24 00:16:33 -0700489 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
490 if (mRestorePackage < 0) throw new IllegalStateException("nextRestorePackage not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700491 if (mRestoreType != RestoreDescription.TYPE_KEY_VALUE) {
492 throw new IllegalStateException("getRestoreData(fd) for non-key/value dataset");
493 }
Christopher Tate51fea572014-06-23 17:01:06 -0700494 File packageDir = new File(mRestoreSetIncrementalDir,
495 mRestorePackages[mRestorePackage].packageName);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700496
Christopher Tate2fdd4282009-06-12 15:20:04 -0700497 // The restore set is the concatenation of the individual record blobs,
Christopher Tateadfe8b82014-02-04 16:23:32 -0800498 // each of which is a file in the package's directory. We return the
499 // data in lexical order sorted by key, so that apps which use synthetic
500 // keys like BLOB_1, BLOB_2, etc will see the date in the most obvious
501 // order.
502 ArrayList<DecodedFilename> blobs = contentsByKey(packageDir);
Dan Egnor01445162009-09-21 17:04:05 -0700503 if (blobs == null) { // nextRestorePackage() ensures the dir exists, so this is an error
Christopher Tateadfe8b82014-02-04 16:23:32 -0800504 Log.e(TAG, "No keys for package: " + packageDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700505 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700506 }
Dan Egnorefe52642009-06-24 00:16:33 -0700507
508 // We expect at least some data if the directory exists in the first place
Christopher Tateadfe8b82014-02-04 16:23:32 -0800509 if (DEBUG) Log.v(TAG, " getRestoreData() found " + blobs.size() + " key files");
Dan Egnorefe52642009-06-24 00:16:33 -0700510 BackupDataOutput out = new BackupDataOutput(outFd.getFileDescriptor());
511 try {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800512 for (DecodedFilename keyEntry : blobs) {
513 File f = keyEntry.file;
Dan Egnorefe52642009-06-24 00:16:33 -0700514 FileInputStream in = new FileInputStream(f);
515 try {
516 int size = (int) f.length();
517 byte[] buf = new byte[size];
518 in.read(buf);
Christopher Tateadfe8b82014-02-04 16:23:32 -0800519 if (DEBUG) Log.v(TAG, " ... key=" + keyEntry.key + " size=" + size);
520 out.writeEntityHeader(keyEntry.key, size);
Dan Egnorefe52642009-06-24 00:16:33 -0700521 out.writeEntityData(buf, size);
522 } finally {
523 in.close();
524 }
525 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700526 return TRANSPORT_OK;
Dan Egnorefe52642009-06-24 00:16:33 -0700527 } catch (IOException e) {
528 Log.e(TAG, "Unable to read backup records", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700529 return TRANSPORT_ERROR;
Dan Egnorefe52642009-06-24 00:16:33 -0700530 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700531 }
Christopher Tate3a31a932009-06-22 15:10:30 -0700532
Christopher Tateadfe8b82014-02-04 16:23:32 -0800533 static class DecodedFilename implements Comparable<DecodedFilename> {
534 public File file;
535 public String key;
536
537 public DecodedFilename(File f) {
538 file = f;
539 key = new String(Base64.decode(f.getName()));
540 }
541
542 @Override
543 public int compareTo(DecodedFilename other) {
544 // sorts into ascending lexical order by decoded key
545 return key.compareTo(other.key);
546 }
547 }
548
549 // Return a list of the files in the given directory, sorted lexically by
550 // the Base64-decoded file name, not by the on-disk filename
551 private ArrayList<DecodedFilename> contentsByKey(File dir) {
552 File[] allFiles = dir.listFiles();
553 if (allFiles == null || allFiles.length == 0) {
554 return null;
555 }
556
557 // Decode the filenames into keys then sort lexically by key
558 ArrayList<DecodedFilename> contents = new ArrayList<DecodedFilename>();
559 for (File f : allFiles) {
560 contents.add(new DecodedFilename(f));
561 }
562 Collections.sort(contents);
563 return contents;
564 }
565
Christopher Tate5a009f92014-06-19 14:53:18 -0700566 @Override
Dan Egnorefe52642009-06-24 00:16:33 -0700567 public void finishRestore() {
568 if (DEBUG) Log.v(TAG, "finishRestore()");
Christopher Tate5a009f92014-06-19 14:53:18 -0700569 if (mRestoreType == RestoreDescription.TYPE_FULL_STREAM) {
570 resetFullRestoreState();
571 }
572 mRestoreType = 0;
Christopher Tate3a31a932009-06-22 15:10:30 -0700573 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700574
575 // ------------------------------------------------------------------------------------
576 // Full restore handling
577
Christopher Tate5a009f92014-06-19 14:53:18 -0700578 private void resetFullRestoreState() {
Christopher Tate824392b2014-11-14 18:27:36 -0800579 IoUtils.closeQuietly(mCurFullRestoreStream);
Christopher Tate5a009f92014-06-19 14:53:18 -0700580 mCurFullRestoreStream = null;
581 mFullRestoreSocketStream = null;
582 mFullRestoreBuffer = null;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700583 }
584
585 /**
586 * Ask the transport to provide data for the "current" package being restored. The
587 * transport then writes some data to the socket supplied to this call, and returns
588 * the number of bytes written. The system will then read that many bytes and
589 * stream them to the application's agent for restore, then will call this method again
590 * to receive the next chunk of the archive. This sequence will be repeated until the
591 * transport returns zero indicating that all of the package's data has been delivered
592 * (or returns a negative value indicating some sort of hard error condition at the
593 * transport level).
594 *
595 * <p>After this method returns zero, the system will then call
596 * {@link #getNextFullRestorePackage()} to begin the restore process for the next
597 * application, and the sequence begins again.
598 *
599 * @param socket The file descriptor that the transport will use for delivering the
600 * streamed archive.
601 * @return 0 when no more data for the current package is available. A positive value
602 * indicates the presence of that much data to be delivered to the app. A negative
603 * return value is treated as equivalent to {@link BackupTransport#TRANSPORT_ERROR},
604 * indicating a fatal error condition that precludes further restore operations
605 * on the current dataset.
606 */
Christopher Tate5a009f92014-06-19 14:53:18 -0700607 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700608 public int getNextFullRestoreDataChunk(ParcelFileDescriptor socket) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700609 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
610 throw new IllegalStateException("Asked for full restore data for non-stream package");
611 }
612
613 // first chunk?
614 if (mCurFullRestoreStream == null) {
615 final String name = mRestorePackages[mRestorePackage].packageName;
616 if (DEBUG) Log.i(TAG, "Starting full restore of " + name);
617 File dataset = new File(mRestoreSetFullDir, name);
618 try {
619 mCurFullRestoreStream = new FileInputStream(dataset);
620 } catch (IOException e) {
621 // If we can't open the target package's tarball, we return the single-package
622 // error code and let the caller go on to the next package.
623 Log.e(TAG, "Unable to read archive for " + name);
624 return TRANSPORT_PACKAGE_REJECTED;
625 }
626 mFullRestoreSocketStream = new FileOutputStream(socket.getFileDescriptor());
Christopher Tate89101f72014-07-17 19:09:00 -0700627 mFullRestoreBuffer = new byte[2*1024];
Christopher Tate5a009f92014-06-19 14:53:18 -0700628 }
629
630 int nRead;
631 try {
632 nRead = mCurFullRestoreStream.read(mFullRestoreBuffer);
633 if (nRead < 0) {
634 // EOF: tell the caller we're done
635 nRead = NO_MORE_DATA;
636 } else if (nRead == 0) {
637 // This shouldn't happen when reading a FileInputStream; we should always
638 // get either a positive nonzero byte count or -1. Log the situation and
639 // treat it as EOF.
640 Log.w(TAG, "read() of archive file returned 0; treating as EOF");
641 nRead = NO_MORE_DATA;
642 } else {
643 if (DEBUG) {
644 Log.i(TAG, " delivering restore chunk: " + nRead);
645 }
646 mFullRestoreSocketStream.write(mFullRestoreBuffer, 0, nRead);
647 }
648 } catch (IOException e) {
649 return TRANSPORT_ERROR; // Hard error accessing the file; shouldn't happen
650 } finally {
651 // Most transports will need to explicitly close 'socket' here, but this transport
652 // is in the same process as the caller so it can leave it up to the backup manager
653 // to manage both socket fds.
654 }
655
656 return nRead;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700657 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700658
659 /**
660 * If the OS encounters an error while processing {@link RestoreDescription#TYPE_FULL_STREAM}
661 * data for restore, it will invoke this method to tell the transport that it should
662 * abandon the data download for the current package. The OS will then either call
663 * {@link #nextRestorePackage()} again to move on to restoring the next package in the
664 * set being iterated over, or will call {@link #finishRestore()} to shut down the restore
665 * operation.
666 *
667 * @return {@link #TRANSPORT_OK} if the transport was successful in shutting down the
668 * current stream cleanly, or {@link #TRANSPORT_ERROR} to indicate a serious
669 * transport-level failure. If the transport reports an error here, the entire restore
670 * operation will immediately be finished with no further attempts to restore app data.
671 */
672 @Override
673 public int abortFullRestore() {
674 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
675 throw new IllegalStateException("abortFullRestore() but not currently restoring");
676 }
677 resetFullRestoreState();
678 mRestoreType = 0;
679 return TRANSPORT_OK;
680 }
681
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700682}