blob: 50e7bcfb9b22560b7b194a15109e6ad4481f11d3 [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 Tate9ff53a72014-06-03 17:20:07 -070038import java.io.BufferedOutputStream;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070039import java.io.File;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070040import java.io.FileInputStream;
Christopher Tate9ff53a72014-06-03 17:20:07 -070041import java.io.FileNotFoundException;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070042import java.io.FileOutputStream;
43import java.io.IOException;
Christopher Tateadfe8b82014-02-04 16:23:32 -080044import java.util.ArrayList;
Christopher Tate9ff53a72014-06-03 17:20:07 -070045import java.util.Arrays;
Christopher Tateadfe8b82014-02-04 16:23:32 -080046import java.util.Collections;
Christopher Tate9ff53a72014-06-03 17:20:07 -070047import java.util.HashSet;
48import java.util.List;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070049
Elliott Hughesf97c6332014-04-28 16:38:43 -070050import static android.system.OsConstants.*;
Christopher Tateb048c332014-02-21 12:50:21 -080051
Christopher Tate9bbc21a2009-06-10 20:23:25 -070052/**
53 * Backup transport for stashing stuff into a known location on disk, and
54 * later restoring from there. For testing only.
55 */
56
Christopher Tate74318c92014-05-15 19:03:44 -070057public class LocalTransport extends BackupTransport {
Christopher Tate9bbc21a2009-06-10 20:23:25 -070058 private static final String TAG = "LocalTransport";
Ed Heyla50cd8d2014-07-14 23:42:04 -070059 private static final boolean DEBUG = false;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070060
Christopher Tate5cb400b2009-06-25 16:03:14 -070061 private static final String TRANSPORT_DIR_NAME
62 = "com.android.internal.backup.LocalTransport";
63
Chris Tatea8ddef32010-11-10 11:53:26 -080064 private static final String TRANSPORT_DESTINATION_STRING
65 = "Backing up to debug-only private cache";
66
Christopher Tate6a49dd02014-06-16 18:49:25 -070067 private static final String INCREMENTAL_DIR = "_delta";
68 private static final String FULL_DATA_DIR = "_full";
69
Christopher Tateadfe8b82014-02-04 16:23:32 -080070 // The currently-active restore set always has the same (nonzero!) token
71 private static final long CURRENT_SET_TOKEN = 1;
Christopher Tate50c6df02010-01-29 12:48:20 -080072
Christopher Tate9bbc21a2009-06-10 20:23:25 -070073 private Context mContext;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070074 private File mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup");
Christopher Tateadfe8b82014-02-04 16:23:32 -080075 private File mCurrentSetDir = new File(mDataDir, Long.toString(CURRENT_SET_TOKEN));
Christopher Tate6a49dd02014-06-16 18:49:25 -070076 private File mCurrentSetIncrementalDir = new File(mCurrentSetDir, INCREMENTAL_DIR);
77 private File mCurrentSetFullDir = new File(mCurrentSetDir, FULL_DATA_DIR);
Christopher Tateadfe8b82014-02-04 16:23:32 -080078
Dan Egnorefe52642009-06-24 00:16:33 -070079 private PackageInfo[] mRestorePackages = null;
80 private int mRestorePackage = -1; // Index into mRestorePackages
Christopher Tate6a49dd02014-06-16 18:49:25 -070081 private int mRestoreType;
82 private File mRestoreSetDir;
83 private File mRestoreSetIncrementalDir;
84 private File mRestoreSetFullDir;
Christopher Tateadfe8b82014-02-04 16:23:32 -080085 private long mRestoreToken;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070086
Christopher Tate9ff53a72014-06-03 17:20:07 -070087 // Additional bookkeeping for full backup
88 private String mFullTargetPackage;
89 private ParcelFileDescriptor mSocket;
90 private FileInputStream mSocketInputStream;
91 private BufferedOutputStream mFullBackupOutputStream;
92 private byte[] mFullBackupBuffer;
93
94 private File mFullRestoreSetDir;
95 private HashSet<String> mFullRestorePackages;
Christopher Tate5a009f92014-06-19 14:53:18 -070096 private FileInputStream mCurFullRestoreStream;
97 private FileOutputStream mFullRestoreSocketStream;
98 private byte[] mFullRestoreBuffer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070099
100 public LocalTransport(Context context) {
101 mContext = context;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800102 mCurrentSetDir.mkdirs();
Christopher Tate9ff53a72014-06-03 17:20:07 -0700103 mCurrentSetFullDir.mkdir();
104 mCurrentSetIncrementalDir.mkdir();
Christopher Tateadfe8b82014-02-04 16:23:32 -0800105 if (!SELinux.restorecon(mCurrentSetDir)) {
106 Log.e(TAG, "SELinux restorecon failed for " + mCurrentSetDir);
rpcraigebab0ae2012-12-04 09:37:23 -0500107 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700108 }
109
Christopher Tate5a009f92014-06-19 14:53:18 -0700110 @Override
Christopher Tatecefba582013-11-14 18:10:35 -0800111 public String name() {
112 return new ComponentName(mContext, this.getClass()).flattenToShortString();
113 }
114
Christopher Tate5a009f92014-06-19 14:53:18 -0700115 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800116 public Intent configurationIntent() {
117 // The local transport is not user-configurable
118 return null;
119 }
120
Christopher Tate5a009f92014-06-19 14:53:18 -0700121 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800122 public String currentDestinationString() {
123 return TRANSPORT_DESTINATION_STRING;
124 }
Christopher Tate5cb400b2009-06-25 16:03:14 -0700125
Christopher Tate5a009f92014-06-19 14:53:18 -0700126 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700127 public String transportDirName() {
Christopher Tate5cb400b2009-06-25 16:03:14 -0700128 return TRANSPORT_DIR_NAME;
129 }
130
Christopher Tate5a009f92014-06-19 14:53:18 -0700131 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700132 public long requestBackupTime() {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700133 // any time is a good time for local backup
134 return 0;
135 }
136
Christopher Tate5a009f92014-06-19 14:53:18 -0700137 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700138 public int initializeDevice() {
139 if (DEBUG) Log.v(TAG, "wiping all data");
Christopher Tateadfe8b82014-02-04 16:23:32 -0800140 deleteContents(mCurrentSetDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700141 return TRANSPORT_OK;
Dan Egnor01445162009-09-21 17:04:05 -0700142 }
143
Christopher Tate5a009f92014-06-19 14:53:18 -0700144 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700145 public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) {
Christopher Tateb048c332014-02-21 12:50:21 -0800146 if (DEBUG) {
147 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700148 StructStat ss = Os.fstat(data.getFileDescriptor());
Christopher Tateb048c332014-02-21 12:50:21 -0800149 Log.v(TAG, "performBackup() pkg=" + packageInfo.packageName
150 + " size=" + ss.st_size);
151 } catch (ErrnoException e) {
152 Log.w(TAG, "Unable to stat input file in performBackup() on "
153 + packageInfo.packageName);
154 }
155 }
Christopher Tate2fdd4282009-06-12 15:20:04 -0700156
Christopher Tate9ff53a72014-06-03 17:20:07 -0700157 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate2fdd4282009-06-12 15:20:04 -0700158 packageDir.mkdirs();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700159
Christopher Tate2fdd4282009-06-12 15:20:04 -0700160 // Each 'record' in the restore set is kept in its own file, named by
161 // the record key. Wind through the data file, extracting individual
162 // record operations and building a set of all the updates to apply
163 // in this update.
164 BackupDataInput changeSet = new BackupDataInput(data.getFileDescriptor());
165 try {
166 int bufSize = 512;
167 byte[] buf = new byte[bufSize];
168 while (changeSet.readNextHeader()) {
169 String key = changeSet.getKey();
Joe Onorato5d605dc2009-06-18 18:23:43 -0700170 String base64Key = new String(Base64.encode(key.getBytes()));
171 File entityFile = new File(packageDir, base64Key);
172
Christopher Tate2fdd4282009-06-12 15:20:04 -0700173 int dataSize = changeSet.getDataSize();
Christopher Tatee9190a22009-06-17 17:52:05 -0700174
Christopher Tatee9190a22009-06-17 17:52:05 -0700175 if (DEBUG) Log.v(TAG, "Got change set key=" + key + " size=" + dataSize
176 + " key64=" + base64Key);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700177
Joe Onorato5d605dc2009-06-18 18:23:43 -0700178 if (dataSize >= 0) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700179 if (entityFile.exists()) {
180 entityFile.delete();
181 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700182 FileOutputStream entity = new FileOutputStream(entityFile);
183
184 if (dataSize > bufSize) {
185 bufSize = dataSize;
186 buf = new byte[bufSize];
187 }
188 changeSet.readEntityData(buf, 0, dataSize);
Christopher Tateb048c332014-02-21 12:50:21 -0800189 if (DEBUG) {
190 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700191 long cur = Os.lseek(data.getFileDescriptor(), 0, SEEK_CUR);
Christopher Tateb048c332014-02-21 12:50:21 -0800192 Log.v(TAG, " read entity data; new pos=" + cur);
193 }
194 catch (ErrnoException e) {
195 Log.w(TAG, "Unable to stat input file in performBackup() on "
196 + packageInfo.packageName);
197 }
198 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700199
200 try {
201 entity.write(buf, 0, dataSize);
202 } catch (IOException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700203 Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath());
Christopher Tate5a009f92014-06-19 14:53:18 -0700204 return TRANSPORT_ERROR;
Joe Onorato5d605dc2009-06-18 18:23:43 -0700205 } finally {
206 entity.close();
207 }
208 } else {
209 entityFile.delete();
Christopher Tate2fdd4282009-06-12 15:20:04 -0700210 }
211 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700212 return TRANSPORT_OK;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700213 } catch (IOException e) {
214 // oops, something went wrong. abort the operation and return error.
Dan Egnorefe52642009-06-24 00:16:33 -0700215 Log.v(TAG, "Exception reading backup input:", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700216 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700217 }
Dan Egnorefe52642009-06-24 00:16:33 -0700218 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700219
Christopher Tate25a747f2009-09-20 12:43:58 -0700220 // Deletes the contents but not the given directory
221 private void deleteContents(File dirname) {
222 File[] contents = dirname.listFiles();
223 if (contents != null) {
224 for (File f : contents) {
225 if (f.isDirectory()) {
226 // delete the directory's contents then fall through
227 // and delete the directory itself.
228 deleteContents(f);
229 }
230 f.delete();
231 }
232 }
233 }
234
Christopher Tate5a009f92014-06-19 14:53:18 -0700235 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700236 public int clearBackupData(PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700237 if (DEBUG) Log.v(TAG, "clearBackupData() pkg=" + packageInfo.packageName);
238
Christopher Tate9ff53a72014-06-03 17:20:07 -0700239 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate0abf6a02012-03-23 17:45:15 -0700240 final File[] fileset = packageDir.listFiles();
241 if (fileset != null) {
242 for (File f : fileset) {
243 f.delete();
244 }
245 packageDir.delete();
Christopher Tateee0e78a2009-07-02 11:17:03 -0700246 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700247
248 packageDir = new File(mCurrentSetFullDir, packageInfo.packageName);
249 final File[] tarballs = packageDir.listFiles();
250 if (tarballs != null) {
251 for (File f : tarballs) {
252 f.delete();
253 }
254 packageDir.delete();
255 }
256
Christopher Tate5a009f92014-06-19 14:53:18 -0700257 return TRANSPORT_OK;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700258 }
259
Christopher Tate5a009f92014-06-19 14:53:18 -0700260 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700261 public int finishBackup() {
Dan Egnorefe52642009-06-24 00:16:33 -0700262 if (DEBUG) Log.v(TAG, "finishBackup()");
Christopher Tate9ff53a72014-06-03 17:20:07 -0700263 if (mSocket != null) {
264 if (DEBUG) {
265 Log.v(TAG, "Concluding full backup of " + mFullTargetPackage);
266 }
267 try {
268 mFullBackupOutputStream.flush();
269 mFullBackupOutputStream.close();
270 mSocketInputStream = null;
271 mFullTargetPackage = null;
272 mSocket.close();
273 } catch (IOException e) {
Christopher Tate89101f72014-07-17 19:09:00 -0700274 if (DEBUG) {
275 Log.w(TAG, "Exception caught in finishBackup()", e);
276 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700277 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700278 } finally {
279 mSocket = null;
280 }
281 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700282 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700283 }
284
Christopher Tate9ff53a72014-06-03 17:20:07 -0700285 // ------------------------------------------------------------------------------------
286 // Full backup handling
Christopher Tate5a009f92014-06-19 14:53:18 -0700287
288 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700289 public long requestFullBackupTime() {
290 return 0;
291 }
292
Christopher Tate5a009f92014-06-19 14:53:18 -0700293 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700294 public int performFullBackup(PackageInfo targetPackage, ParcelFileDescriptor socket) {
295 if (mSocket != null) {
296 Log.e(TAG, "Attempt to initiate full backup while one is in progress");
Christopher Tate5a009f92014-06-19 14:53:18 -0700297 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700298 }
299
300 if (DEBUG) {
301 Log.i(TAG, "performFullBackup : " + targetPackage);
302 }
303
304 // We know a priori that we run in the system process, so we need to make
305 // sure to dup() our own copy of the socket fd. Transports which run in
306 // their own processes must not do this.
307 try {
308 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
309 mSocketInputStream = new FileInputStream(mSocket.getFileDescriptor());
310 } catch (IOException e) {
311 Log.e(TAG, "Unable to process socket for full backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700312 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700313 }
314
315 mFullTargetPackage = targetPackage.packageName;
316 FileOutputStream tarstream;
317 try {
318 File tarball = new File(mCurrentSetFullDir, mFullTargetPackage);
319 tarstream = new FileOutputStream(tarball);
320 } catch (FileNotFoundException e) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700321 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700322 }
323 mFullBackupOutputStream = new BufferedOutputStream(tarstream);
324 mFullBackupBuffer = new byte[4096];
325
Christopher Tate5a009f92014-06-19 14:53:18 -0700326 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700327 }
328
Christopher Tate5a009f92014-06-19 14:53:18 -0700329 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700330 public int sendBackupData(int numBytes) {
331 if (mFullBackupBuffer == null) {
332 Log.w(TAG, "Attempted sendBackupData before performFullBackup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700333 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700334 }
335
336 if (numBytes > mFullBackupBuffer.length) {
337 mFullBackupBuffer = new byte[numBytes];
338 }
339 while (numBytes > 0) {
340 try {
341 int nRead = mSocketInputStream.read(mFullBackupBuffer, 0, numBytes);
342 if (nRead < 0) {
343 // Something went wrong if we expect data but saw EOD
344 Log.w(TAG, "Unexpected EOD; failing backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700345 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700346 }
347 mFullBackupOutputStream.write(mFullBackupBuffer, 0, nRead);
348 numBytes -= nRead;
349 } catch (IOException e) {
350 Log.e(TAG, "Error handling backup data for " + mFullTargetPackage);
Christopher Tate5a009f92014-06-19 14:53:18 -0700351 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700352 }
353 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700354 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700355 }
356
357 // ------------------------------------------------------------------------------------
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700358 // Restore handling
Christopher Tate51fea572014-06-23 17:01:06 -0700359 static final long[] POSSIBLE_SETS = { 2, 3, 4, 5, 6, 7, 8, 9 };
Christopher Tate5a009f92014-06-19 14:53:18 -0700360
361 @Override
Christopher Tate74318c92014-05-15 19:03:44 -0700362 public RestoreSet[] getAvailableRestoreSets() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800363 long[] existing = new long[POSSIBLE_SETS.length + 1];
364 int num = 0;
365
Christopher Tate9ff53a72014-06-03 17:20:07 -0700366 // see which possible non-current sets exist...
Christopher Tateadfe8b82014-02-04 16:23:32 -0800367 for (long token : POSSIBLE_SETS) {
368 if ((new File(mDataDir, Long.toString(token))).exists()) {
369 existing[num++] = token;
370 }
371 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700372 // ...and always the currently-active set last
Christopher Tateadfe8b82014-02-04 16:23:32 -0800373 existing[num++] = CURRENT_SET_TOKEN;
374
375 RestoreSet[] available = new RestoreSet[num];
376 for (int i = 0; i < available.length; i++) {
377 available[i] = new RestoreSet("Local disk image", "flash", existing[i]);
378 }
379 return available;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700380 }
381
Christopher Tate5a009f92014-06-19 14:53:18 -0700382 @Override
Christopher Tate50c6df02010-01-29 12:48:20 -0800383 public long getCurrentRestoreSet() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800384 // The current restore set always has the same token
385 return CURRENT_SET_TOKEN;
Christopher Tate50c6df02010-01-29 12:48:20 -0800386 }
387
Christopher Tate5a009f92014-06-19 14:53:18 -0700388 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700389 public int startRestore(long token, PackageInfo[] packages) {
Christopher Tate51fea572014-06-23 17:01:06 -0700390 if (DEBUG) Log.v(TAG, "start restore " + token + " : " + packages.length
391 + " matching packages");
Dan Egnorefe52642009-06-24 00:16:33 -0700392 mRestorePackages = packages;
393 mRestorePackage = -1;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800394 mRestoreToken = token;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700395 mRestoreSetDir = new File(mDataDir, Long.toString(token));
396 mRestoreSetIncrementalDir = new File(mRestoreSetDir, INCREMENTAL_DIR);
397 mRestoreSetFullDir = new File(mRestoreSetDir, FULL_DATA_DIR);
Christopher Tate5a009f92014-06-19 14:53:18 -0700398 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700399 }
400
Christopher Tate6a49dd02014-06-16 18:49:25 -0700401 @Override
402 public RestoreDescription nextRestorePackage() {
Dan Egnorefe52642009-06-24 00:16:33 -0700403 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700404
405 boolean found = false;
Dan Egnorefe52642009-06-24 00:16:33 -0700406 while (++mRestorePackage < mRestorePackages.length) {
407 String name = mRestorePackages[mRestorePackage].packageName;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700408
409 // If we have key/value data for this package, deliver that
Christopher Tatea9b91862014-02-25 17:42:21 -0800410 // skip packages where we have a data dir but no actual contents
Christopher Tate6a49dd02014-06-16 18:49:25 -0700411 String[] contents = (new File(mRestoreSetIncrementalDir, name)).list();
Christopher Tatea9b91862014-02-25 17:42:21 -0800412 if (contents != null && contents.length > 0) {
Christopher Tate6a49dd02014-06-16 18:49:25 -0700413 if (DEBUG) Log.v(TAG, " nextRestorePackage(TYPE_KEY_VALUE) = " + name);
414 mRestoreType = RestoreDescription.TYPE_KEY_VALUE;
415 found = true;
416 }
417
418 if (!found) {
419 // No key/value data; check for [non-empty] full data
420 File maybeFullData = new File(mRestoreSetFullDir, name);
421 if (maybeFullData.length() > 0) {
422 if (DEBUG) Log.v(TAG, " nextRestorePackage(TYPE_FULL_STREAM) = " + name);
423 mRestoreType = RestoreDescription.TYPE_FULL_STREAM;
Christopher Tate5a009f92014-06-19 14:53:18 -0700424 mCurFullRestoreStream = null; // ensure starting from the ground state
Christopher Tate6a49dd02014-06-16 18:49:25 -0700425 found = true;
426 }
427 }
428
429 if (found) {
430 return new RestoreDescription(name, mRestoreType);
Dan Egnorefe52642009-06-24 00:16:33 -0700431 }
432 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700433
Dan Egnorefe52642009-06-24 00:16:33 -0700434 if (DEBUG) Log.v(TAG, " no more packages to restore");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700435 return RestoreDescription.NO_MORE_PACKAGES;
Dan Egnorefe52642009-06-24 00:16:33 -0700436 }
437
Christopher Tate5a009f92014-06-19 14:53:18 -0700438 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700439 public int getRestoreData(ParcelFileDescriptor outFd) {
Dan Egnorefe52642009-06-24 00:16:33 -0700440 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
441 if (mRestorePackage < 0) throw new IllegalStateException("nextRestorePackage not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700442 if (mRestoreType != RestoreDescription.TYPE_KEY_VALUE) {
443 throw new IllegalStateException("getRestoreData(fd) for non-key/value dataset");
444 }
Christopher Tate51fea572014-06-23 17:01:06 -0700445 File packageDir = new File(mRestoreSetIncrementalDir,
446 mRestorePackages[mRestorePackage].packageName);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700447
Christopher Tate2fdd4282009-06-12 15:20:04 -0700448 // The restore set is the concatenation of the individual record blobs,
Christopher Tateadfe8b82014-02-04 16:23:32 -0800449 // each of which is a file in the package's directory. We return the
450 // data in lexical order sorted by key, so that apps which use synthetic
451 // keys like BLOB_1, BLOB_2, etc will see the date in the most obvious
452 // order.
453 ArrayList<DecodedFilename> blobs = contentsByKey(packageDir);
Dan Egnor01445162009-09-21 17:04:05 -0700454 if (blobs == null) { // nextRestorePackage() ensures the dir exists, so this is an error
Christopher Tateadfe8b82014-02-04 16:23:32 -0800455 Log.e(TAG, "No keys for package: " + packageDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700456 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700457 }
Dan Egnorefe52642009-06-24 00:16:33 -0700458
459 // We expect at least some data if the directory exists in the first place
Christopher Tateadfe8b82014-02-04 16:23:32 -0800460 if (DEBUG) Log.v(TAG, " getRestoreData() found " + blobs.size() + " key files");
Dan Egnorefe52642009-06-24 00:16:33 -0700461 BackupDataOutput out = new BackupDataOutput(outFd.getFileDescriptor());
462 try {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800463 for (DecodedFilename keyEntry : blobs) {
464 File f = keyEntry.file;
Dan Egnorefe52642009-06-24 00:16:33 -0700465 FileInputStream in = new FileInputStream(f);
466 try {
467 int size = (int) f.length();
468 byte[] buf = new byte[size];
469 in.read(buf);
Christopher Tateadfe8b82014-02-04 16:23:32 -0800470 if (DEBUG) Log.v(TAG, " ... key=" + keyEntry.key + " size=" + size);
471 out.writeEntityHeader(keyEntry.key, size);
Dan Egnorefe52642009-06-24 00:16:33 -0700472 out.writeEntityData(buf, size);
473 } finally {
474 in.close();
475 }
476 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700477 return TRANSPORT_OK;
Dan Egnorefe52642009-06-24 00:16:33 -0700478 } catch (IOException e) {
479 Log.e(TAG, "Unable to read backup records", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700480 return TRANSPORT_ERROR;
Dan Egnorefe52642009-06-24 00:16:33 -0700481 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700482 }
Christopher Tate3a31a932009-06-22 15:10:30 -0700483
Christopher Tateadfe8b82014-02-04 16:23:32 -0800484 static class DecodedFilename implements Comparable<DecodedFilename> {
485 public File file;
486 public String key;
487
488 public DecodedFilename(File f) {
489 file = f;
490 key = new String(Base64.decode(f.getName()));
491 }
492
493 @Override
494 public int compareTo(DecodedFilename other) {
495 // sorts into ascending lexical order by decoded key
496 return key.compareTo(other.key);
497 }
498 }
499
500 // Return a list of the files in the given directory, sorted lexically by
501 // the Base64-decoded file name, not by the on-disk filename
502 private ArrayList<DecodedFilename> contentsByKey(File dir) {
503 File[] allFiles = dir.listFiles();
504 if (allFiles == null || allFiles.length == 0) {
505 return null;
506 }
507
508 // Decode the filenames into keys then sort lexically by key
509 ArrayList<DecodedFilename> contents = new ArrayList<DecodedFilename>();
510 for (File f : allFiles) {
511 contents.add(new DecodedFilename(f));
512 }
513 Collections.sort(contents);
514 return contents;
515 }
516
Christopher Tate5a009f92014-06-19 14:53:18 -0700517 @Override
Dan Egnorefe52642009-06-24 00:16:33 -0700518 public void finishRestore() {
519 if (DEBUG) Log.v(TAG, "finishRestore()");
Christopher Tate5a009f92014-06-19 14:53:18 -0700520 if (mRestoreType == RestoreDescription.TYPE_FULL_STREAM) {
521 resetFullRestoreState();
522 }
523 mRestoreType = 0;
Christopher Tate3a31a932009-06-22 15:10:30 -0700524 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700525
526 // ------------------------------------------------------------------------------------
527 // Full restore handling
528
Christopher Tate5a009f92014-06-19 14:53:18 -0700529 private void resetFullRestoreState() {
530 try {
531 mCurFullRestoreStream.close();
532 } catch (IOException e) {
533 Log.w(TAG, "Unable to close full restore input stream");
Christopher Tate9ff53a72014-06-03 17:20:07 -0700534 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700535 mCurFullRestoreStream = null;
536 mFullRestoreSocketStream = null;
537 mFullRestoreBuffer = null;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700538 }
539
540 /**
541 * Ask the transport to provide data for the "current" package being restored. The
542 * transport then writes some data to the socket supplied to this call, and returns
543 * the number of bytes written. The system will then read that many bytes and
544 * stream them to the application's agent for restore, then will call this method again
545 * to receive the next chunk of the archive. This sequence will be repeated until the
546 * transport returns zero indicating that all of the package's data has been delivered
547 * (or returns a negative value indicating some sort of hard error condition at the
548 * transport level).
549 *
550 * <p>After this method returns zero, the system will then call
551 * {@link #getNextFullRestorePackage()} to begin the restore process for the next
552 * application, and the sequence begins again.
553 *
554 * @param socket The file descriptor that the transport will use for delivering the
555 * streamed archive.
556 * @return 0 when no more data for the current package is available. A positive value
557 * indicates the presence of that much data to be delivered to the app. A negative
558 * return value is treated as equivalent to {@link BackupTransport#TRANSPORT_ERROR},
559 * indicating a fatal error condition that precludes further restore operations
560 * on the current dataset.
561 */
Christopher Tate5a009f92014-06-19 14:53:18 -0700562 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700563 public int getNextFullRestoreDataChunk(ParcelFileDescriptor socket) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700564 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
565 throw new IllegalStateException("Asked for full restore data for non-stream package");
566 }
567
568 // first chunk?
569 if (mCurFullRestoreStream == null) {
570 final String name = mRestorePackages[mRestorePackage].packageName;
571 if (DEBUG) Log.i(TAG, "Starting full restore of " + name);
572 File dataset = new File(mRestoreSetFullDir, name);
573 try {
574 mCurFullRestoreStream = new FileInputStream(dataset);
575 } catch (IOException e) {
576 // If we can't open the target package's tarball, we return the single-package
577 // error code and let the caller go on to the next package.
578 Log.e(TAG, "Unable to read archive for " + name);
579 return TRANSPORT_PACKAGE_REJECTED;
580 }
581 mFullRestoreSocketStream = new FileOutputStream(socket.getFileDescriptor());
Christopher Tate89101f72014-07-17 19:09:00 -0700582 mFullRestoreBuffer = new byte[2*1024];
Christopher Tate5a009f92014-06-19 14:53:18 -0700583 }
584
585 int nRead;
586 try {
587 nRead = mCurFullRestoreStream.read(mFullRestoreBuffer);
588 if (nRead < 0) {
589 // EOF: tell the caller we're done
590 nRead = NO_MORE_DATA;
591 } else if (nRead == 0) {
592 // This shouldn't happen when reading a FileInputStream; we should always
593 // get either a positive nonzero byte count or -1. Log the situation and
594 // treat it as EOF.
595 Log.w(TAG, "read() of archive file returned 0; treating as EOF");
596 nRead = NO_MORE_DATA;
597 } else {
598 if (DEBUG) {
599 Log.i(TAG, " delivering restore chunk: " + nRead);
600 }
601 mFullRestoreSocketStream.write(mFullRestoreBuffer, 0, nRead);
602 }
603 } catch (IOException e) {
604 return TRANSPORT_ERROR; // Hard error accessing the file; shouldn't happen
605 } finally {
606 // Most transports will need to explicitly close 'socket' here, but this transport
607 // is in the same process as the caller so it can leave it up to the backup manager
608 // to manage both socket fds.
609 }
610
611 return nRead;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700612 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700613
614 /**
615 * If the OS encounters an error while processing {@link RestoreDescription#TYPE_FULL_STREAM}
616 * data for restore, it will invoke this method to tell the transport that it should
617 * abandon the data download for the current package. The OS will then either call
618 * {@link #nextRestorePackage()} again to move on to restoring the next package in the
619 * set being iterated over, or will call {@link #finishRestore()} to shut down the restore
620 * operation.
621 *
622 * @return {@link #TRANSPORT_OK} if the transport was successful in shutting down the
623 * current stream cleanly, or {@link #TRANSPORT_ERROR} to indicate a serious
624 * transport-level failure. If the transport reports an error here, the entire restore
625 * operation will immediately be finished with no further attempts to restore app data.
626 */
627 @Override
628 public int abortFullRestore() {
629 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
630 throw new IllegalStateException("abortFullRestore() but not currently restoring");
631 }
632 resetFullRestoreState();
633 mRestoreType = 0;
634 return TRANSPORT_OK;
635 }
636
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700637}