blob: 97e1102d8cac4354ea02e41bbc99db179c456a43 [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 Tate96794102014-07-27 20:21:55 -070067 private static final String TRANSPORT_DATA_MANAGEMENT_LABEL
68 = "";
69
Christopher Tate6a49dd02014-06-16 18:49:25 -070070 private static final String INCREMENTAL_DIR = "_delta";
71 private static final String FULL_DATA_DIR = "_full";
72
Christopher Tateadfe8b82014-02-04 16:23:32 -080073 // The currently-active restore set always has the same (nonzero!) token
74 private static final long CURRENT_SET_TOKEN = 1;
Christopher Tate50c6df02010-01-29 12:48:20 -080075
Christopher Tate9bbc21a2009-06-10 20:23:25 -070076 private Context mContext;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070077 private File mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup");
Christopher Tateadfe8b82014-02-04 16:23:32 -080078 private File mCurrentSetDir = new File(mDataDir, Long.toString(CURRENT_SET_TOKEN));
Christopher Tate6a49dd02014-06-16 18:49:25 -070079 private File mCurrentSetIncrementalDir = new File(mCurrentSetDir, INCREMENTAL_DIR);
80 private File mCurrentSetFullDir = new File(mCurrentSetDir, FULL_DATA_DIR);
Christopher Tateadfe8b82014-02-04 16:23:32 -080081
Dan Egnorefe52642009-06-24 00:16:33 -070082 private PackageInfo[] mRestorePackages = null;
83 private int mRestorePackage = -1; // Index into mRestorePackages
Christopher Tate6a49dd02014-06-16 18:49:25 -070084 private int mRestoreType;
85 private File mRestoreSetDir;
86 private File mRestoreSetIncrementalDir;
87 private File mRestoreSetFullDir;
Christopher Tateadfe8b82014-02-04 16:23:32 -080088 private long mRestoreToken;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070089
Christopher Tate9ff53a72014-06-03 17:20:07 -070090 // Additional bookkeeping for full backup
91 private String mFullTargetPackage;
92 private ParcelFileDescriptor mSocket;
93 private FileInputStream mSocketInputStream;
94 private BufferedOutputStream mFullBackupOutputStream;
95 private byte[] mFullBackupBuffer;
96
97 private File mFullRestoreSetDir;
98 private HashSet<String> mFullRestorePackages;
Christopher Tate5a009f92014-06-19 14:53:18 -070099 private FileInputStream mCurFullRestoreStream;
100 private FileOutputStream mFullRestoreSocketStream;
101 private byte[] mFullRestoreBuffer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700102
103 public LocalTransport(Context context) {
104 mContext = context;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800105 mCurrentSetDir.mkdirs();
Christopher Tate9ff53a72014-06-03 17:20:07 -0700106 mCurrentSetFullDir.mkdir();
107 mCurrentSetIncrementalDir.mkdir();
Christopher Tateadfe8b82014-02-04 16:23:32 -0800108 if (!SELinux.restorecon(mCurrentSetDir)) {
109 Log.e(TAG, "SELinux restorecon failed for " + mCurrentSetDir);
rpcraigebab0ae2012-12-04 09:37:23 -0500110 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700111 }
112
Christopher Tate5a009f92014-06-19 14:53:18 -0700113 @Override
Christopher Tatecefba582013-11-14 18:10:35 -0800114 public String name() {
115 return new ComponentName(mContext, this.getClass()).flattenToShortString();
116 }
117
Christopher Tate5a009f92014-06-19 14:53:18 -0700118 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800119 public Intent configurationIntent() {
120 // The local transport is not user-configurable
121 return null;
122 }
123
Christopher Tate5a009f92014-06-19 14:53:18 -0700124 @Override
Chris Tatea8ddef32010-11-10 11:53:26 -0800125 public String currentDestinationString() {
126 return TRANSPORT_DESTINATION_STRING;
127 }
Christopher Tate5cb400b2009-06-25 16:03:14 -0700128
Christopher Tate96794102014-07-27 20:21:55 -0700129 public Intent dataManagementIntent() {
130 // The local transport does not present a data-management UI
131 // TODO: consider adding simple UI to wipe the archives entirely,
132 // for cleaning up the cache partition.
133 return null;
134 }
135
136 public String dataManagementLabel() {
137 return TRANSPORT_DATA_MANAGEMENT_LABEL;
138 }
139
Christopher Tate5a009f92014-06-19 14:53:18 -0700140 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700141 public String transportDirName() {
Christopher Tate5cb400b2009-06-25 16:03:14 -0700142 return TRANSPORT_DIR_NAME;
143 }
144
Christopher Tate5a009f92014-06-19 14:53:18 -0700145 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700146 public long requestBackupTime() {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700147 // any time is a good time for local backup
148 return 0;
149 }
150
Christopher Tate5a009f92014-06-19 14:53:18 -0700151 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700152 public int initializeDevice() {
153 if (DEBUG) Log.v(TAG, "wiping all data");
Christopher Tateadfe8b82014-02-04 16:23:32 -0800154 deleteContents(mCurrentSetDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700155 return TRANSPORT_OK;
Dan Egnor01445162009-09-21 17:04:05 -0700156 }
157
Christopher Tate5a009f92014-06-19 14:53:18 -0700158 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700159 public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) {
Christopher Tateb048c332014-02-21 12:50:21 -0800160 if (DEBUG) {
161 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700162 StructStat ss = Os.fstat(data.getFileDescriptor());
Christopher Tateb048c332014-02-21 12:50:21 -0800163 Log.v(TAG, "performBackup() pkg=" + packageInfo.packageName
164 + " size=" + ss.st_size);
165 } catch (ErrnoException e) {
166 Log.w(TAG, "Unable to stat input file in performBackup() on "
167 + packageInfo.packageName);
168 }
169 }
Christopher Tate2fdd4282009-06-12 15:20:04 -0700170
Christopher Tate9ff53a72014-06-03 17:20:07 -0700171 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate2fdd4282009-06-12 15:20:04 -0700172 packageDir.mkdirs();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700173
Christopher Tate2fdd4282009-06-12 15:20:04 -0700174 // Each 'record' in the restore set is kept in its own file, named by
175 // the record key. Wind through the data file, extracting individual
176 // record operations and building a set of all the updates to apply
177 // in this update.
178 BackupDataInput changeSet = new BackupDataInput(data.getFileDescriptor());
179 try {
180 int bufSize = 512;
181 byte[] buf = new byte[bufSize];
182 while (changeSet.readNextHeader()) {
183 String key = changeSet.getKey();
Joe Onorato5d605dc2009-06-18 18:23:43 -0700184 String base64Key = new String(Base64.encode(key.getBytes()));
185 File entityFile = new File(packageDir, base64Key);
186
Christopher Tate2fdd4282009-06-12 15:20:04 -0700187 int dataSize = changeSet.getDataSize();
Christopher Tatee9190a22009-06-17 17:52:05 -0700188
Christopher Tatee9190a22009-06-17 17:52:05 -0700189 if (DEBUG) Log.v(TAG, "Got change set key=" + key + " size=" + dataSize
190 + " key64=" + base64Key);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700191
Joe Onorato5d605dc2009-06-18 18:23:43 -0700192 if (dataSize >= 0) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700193 if (entityFile.exists()) {
194 entityFile.delete();
195 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700196 FileOutputStream entity = new FileOutputStream(entityFile);
197
198 if (dataSize > bufSize) {
199 bufSize = dataSize;
200 buf = new byte[bufSize];
201 }
202 changeSet.readEntityData(buf, 0, dataSize);
Christopher Tateb048c332014-02-21 12:50:21 -0800203 if (DEBUG) {
204 try {
Elliott Hughesf97c6332014-04-28 16:38:43 -0700205 long cur = Os.lseek(data.getFileDescriptor(), 0, SEEK_CUR);
Christopher Tateb048c332014-02-21 12:50:21 -0800206 Log.v(TAG, " read entity data; new pos=" + cur);
207 }
208 catch (ErrnoException e) {
209 Log.w(TAG, "Unable to stat input file in performBackup() on "
210 + packageInfo.packageName);
211 }
212 }
Joe Onorato5d605dc2009-06-18 18:23:43 -0700213
214 try {
215 entity.write(buf, 0, dataSize);
216 } catch (IOException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700217 Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath());
Christopher Tate5a009f92014-06-19 14:53:18 -0700218 return TRANSPORT_ERROR;
Joe Onorato5d605dc2009-06-18 18:23:43 -0700219 } finally {
220 entity.close();
221 }
222 } else {
223 entityFile.delete();
Christopher Tate2fdd4282009-06-12 15:20:04 -0700224 }
225 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700226 return TRANSPORT_OK;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700227 } catch (IOException e) {
228 // oops, something went wrong. abort the operation and return error.
Dan Egnorefe52642009-06-24 00:16:33 -0700229 Log.v(TAG, "Exception reading backup input:", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700230 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700231 }
Dan Egnorefe52642009-06-24 00:16:33 -0700232 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700233
Christopher Tate25a747f2009-09-20 12:43:58 -0700234 // Deletes the contents but not the given directory
235 private void deleteContents(File dirname) {
236 File[] contents = dirname.listFiles();
237 if (contents != null) {
238 for (File f : contents) {
239 if (f.isDirectory()) {
240 // delete the directory's contents then fall through
241 // and delete the directory itself.
242 deleteContents(f);
243 }
244 f.delete();
245 }
246 }
247 }
248
Christopher Tate5a009f92014-06-19 14:53:18 -0700249 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700250 public int clearBackupData(PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700251 if (DEBUG) Log.v(TAG, "clearBackupData() pkg=" + packageInfo.packageName);
252
Christopher Tate9ff53a72014-06-03 17:20:07 -0700253 File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
Christopher Tate0abf6a02012-03-23 17:45:15 -0700254 final File[] fileset = packageDir.listFiles();
255 if (fileset != null) {
256 for (File f : fileset) {
257 f.delete();
258 }
259 packageDir.delete();
Christopher Tateee0e78a2009-07-02 11:17:03 -0700260 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700261
262 packageDir = new File(mCurrentSetFullDir, packageInfo.packageName);
263 final File[] tarballs = packageDir.listFiles();
264 if (tarballs != null) {
265 for (File f : tarballs) {
266 f.delete();
267 }
268 packageDir.delete();
269 }
270
Christopher Tate5a009f92014-06-19 14:53:18 -0700271 return TRANSPORT_OK;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700272 }
273
Christopher Tate5a009f92014-06-19 14:53:18 -0700274 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700275 public int finishBackup() {
Dan Egnorefe52642009-06-24 00:16:33 -0700276 if (DEBUG) Log.v(TAG, "finishBackup()");
Christopher Tate9ff53a72014-06-03 17:20:07 -0700277 if (mSocket != null) {
278 if (DEBUG) {
279 Log.v(TAG, "Concluding full backup of " + mFullTargetPackage);
280 }
281 try {
282 mFullBackupOutputStream.flush();
283 mFullBackupOutputStream.close();
284 mSocketInputStream = null;
285 mFullTargetPackage = null;
286 mSocket.close();
287 } catch (IOException e) {
Christopher Tate89101f72014-07-17 19:09:00 -0700288 if (DEBUG) {
289 Log.w(TAG, "Exception caught in finishBackup()", e);
290 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700291 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700292 } finally {
293 mSocket = null;
294 }
295 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700296 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700297 }
298
Christopher Tate9ff53a72014-06-03 17:20:07 -0700299 // ------------------------------------------------------------------------------------
300 // Full backup handling
Christopher Tate5a009f92014-06-19 14:53:18 -0700301
302 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700303 public long requestFullBackupTime() {
304 return 0;
305 }
306
Christopher Tate5a009f92014-06-19 14:53:18 -0700307 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700308 public int performFullBackup(PackageInfo targetPackage, ParcelFileDescriptor socket) {
309 if (mSocket != null) {
310 Log.e(TAG, "Attempt to initiate full backup while one is in progress");
Christopher Tate5a009f92014-06-19 14:53:18 -0700311 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700312 }
313
314 if (DEBUG) {
315 Log.i(TAG, "performFullBackup : " + targetPackage);
316 }
317
318 // We know a priori that we run in the system process, so we need to make
319 // sure to dup() our own copy of the socket fd. Transports which run in
320 // their own processes must not do this.
321 try {
322 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
323 mSocketInputStream = new FileInputStream(mSocket.getFileDescriptor());
324 } catch (IOException e) {
325 Log.e(TAG, "Unable to process socket for full backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700326 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700327 }
328
329 mFullTargetPackage = targetPackage.packageName;
330 FileOutputStream tarstream;
331 try {
332 File tarball = new File(mCurrentSetFullDir, mFullTargetPackage);
333 tarstream = new FileOutputStream(tarball);
334 } catch (FileNotFoundException e) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700335 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700336 }
337 mFullBackupOutputStream = new BufferedOutputStream(tarstream);
338 mFullBackupBuffer = new byte[4096];
339
Christopher Tate5a009f92014-06-19 14:53:18 -0700340 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700341 }
342
Christopher Tate5a009f92014-06-19 14:53:18 -0700343 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700344 public int sendBackupData(int numBytes) {
345 if (mFullBackupBuffer == null) {
346 Log.w(TAG, "Attempted sendBackupData before performFullBackup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700347 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700348 }
349
350 if (numBytes > mFullBackupBuffer.length) {
351 mFullBackupBuffer = new byte[numBytes];
352 }
353 while (numBytes > 0) {
354 try {
355 int nRead = mSocketInputStream.read(mFullBackupBuffer, 0, numBytes);
356 if (nRead < 0) {
357 // Something went wrong if we expect data but saw EOD
358 Log.w(TAG, "Unexpected EOD; failing backup");
Christopher Tate5a009f92014-06-19 14:53:18 -0700359 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700360 }
361 mFullBackupOutputStream.write(mFullBackupBuffer, 0, nRead);
362 numBytes -= nRead;
363 } catch (IOException e) {
364 Log.e(TAG, "Error handling backup data for " + mFullTargetPackage);
Christopher Tate5a009f92014-06-19 14:53:18 -0700365 return TRANSPORT_ERROR;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700366 }
367 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700368 return TRANSPORT_OK;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700369 }
370
371 // ------------------------------------------------------------------------------------
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700372 // Restore handling
Christopher Tate51fea572014-06-23 17:01:06 -0700373 static final long[] POSSIBLE_SETS = { 2, 3, 4, 5, 6, 7, 8, 9 };
Christopher Tate5a009f92014-06-19 14:53:18 -0700374
375 @Override
Christopher Tate74318c92014-05-15 19:03:44 -0700376 public RestoreSet[] getAvailableRestoreSets() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800377 long[] existing = new long[POSSIBLE_SETS.length + 1];
378 int num = 0;
379
Christopher Tate9ff53a72014-06-03 17:20:07 -0700380 // see which possible non-current sets exist...
Christopher Tateadfe8b82014-02-04 16:23:32 -0800381 for (long token : POSSIBLE_SETS) {
382 if ((new File(mDataDir, Long.toString(token))).exists()) {
383 existing[num++] = token;
384 }
385 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700386 // ...and always the currently-active set last
Christopher Tateadfe8b82014-02-04 16:23:32 -0800387 existing[num++] = CURRENT_SET_TOKEN;
388
389 RestoreSet[] available = new RestoreSet[num];
390 for (int i = 0; i < available.length; i++) {
391 available[i] = new RestoreSet("Local disk image", "flash", existing[i]);
392 }
393 return available;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700394 }
395
Christopher Tate5a009f92014-06-19 14:53:18 -0700396 @Override
Christopher Tate50c6df02010-01-29 12:48:20 -0800397 public long getCurrentRestoreSet() {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800398 // The current restore set always has the same token
399 return CURRENT_SET_TOKEN;
Christopher Tate50c6df02010-01-29 12:48:20 -0800400 }
401
Christopher Tate5a009f92014-06-19 14:53:18 -0700402 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700403 public int startRestore(long token, PackageInfo[] packages) {
Christopher Tate51fea572014-06-23 17:01:06 -0700404 if (DEBUG) Log.v(TAG, "start restore " + token + " : " + packages.length
405 + " matching packages");
Dan Egnorefe52642009-06-24 00:16:33 -0700406 mRestorePackages = packages;
407 mRestorePackage = -1;
Christopher Tateadfe8b82014-02-04 16:23:32 -0800408 mRestoreToken = token;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700409 mRestoreSetDir = new File(mDataDir, Long.toString(token));
410 mRestoreSetIncrementalDir = new File(mRestoreSetDir, INCREMENTAL_DIR);
411 mRestoreSetFullDir = new File(mRestoreSetDir, FULL_DATA_DIR);
Christopher Tate5a009f92014-06-19 14:53:18 -0700412 return TRANSPORT_OK;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700413 }
414
Christopher Tate6a49dd02014-06-16 18:49:25 -0700415 @Override
416 public RestoreDescription nextRestorePackage() {
Dan Egnorefe52642009-06-24 00:16:33 -0700417 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700418
419 boolean found = false;
Dan Egnorefe52642009-06-24 00:16:33 -0700420 while (++mRestorePackage < mRestorePackages.length) {
421 String name = mRestorePackages[mRestorePackage].packageName;
Christopher Tate6a49dd02014-06-16 18:49:25 -0700422
423 // If we have key/value data for this package, deliver that
Christopher Tatea9b91862014-02-25 17:42:21 -0800424 // skip packages where we have a data dir but no actual contents
Christopher Tate6a49dd02014-06-16 18:49:25 -0700425 String[] contents = (new File(mRestoreSetIncrementalDir, name)).list();
Christopher Tatea9b91862014-02-25 17:42:21 -0800426 if (contents != null && contents.length > 0) {
Christopher Tate6a49dd02014-06-16 18:49:25 -0700427 if (DEBUG) Log.v(TAG, " nextRestorePackage(TYPE_KEY_VALUE) = " + name);
428 mRestoreType = RestoreDescription.TYPE_KEY_VALUE;
429 found = true;
430 }
431
432 if (!found) {
433 // No key/value data; check for [non-empty] full data
434 File maybeFullData = new File(mRestoreSetFullDir, name);
435 if (maybeFullData.length() > 0) {
436 if (DEBUG) Log.v(TAG, " nextRestorePackage(TYPE_FULL_STREAM) = " + name);
437 mRestoreType = RestoreDescription.TYPE_FULL_STREAM;
Christopher Tate5a009f92014-06-19 14:53:18 -0700438 mCurFullRestoreStream = null; // ensure starting from the ground state
Christopher Tate6a49dd02014-06-16 18:49:25 -0700439 found = true;
440 }
441 }
442
443 if (found) {
444 return new RestoreDescription(name, mRestoreType);
Dan Egnorefe52642009-06-24 00:16:33 -0700445 }
446 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700447
Dan Egnorefe52642009-06-24 00:16:33 -0700448 if (DEBUG) Log.v(TAG, " no more packages to restore");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700449 return RestoreDescription.NO_MORE_PACKAGES;
Dan Egnorefe52642009-06-24 00:16:33 -0700450 }
451
Christopher Tate5a009f92014-06-19 14:53:18 -0700452 @Override
Dan Egnor01445162009-09-21 17:04:05 -0700453 public int getRestoreData(ParcelFileDescriptor outFd) {
Dan Egnorefe52642009-06-24 00:16:33 -0700454 if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
455 if (mRestorePackage < 0) throw new IllegalStateException("nextRestorePackage not called");
Christopher Tate6a49dd02014-06-16 18:49:25 -0700456 if (mRestoreType != RestoreDescription.TYPE_KEY_VALUE) {
457 throw new IllegalStateException("getRestoreData(fd) for non-key/value dataset");
458 }
Christopher Tate51fea572014-06-23 17:01:06 -0700459 File packageDir = new File(mRestoreSetIncrementalDir,
460 mRestorePackages[mRestorePackage].packageName);
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700461
Christopher Tate2fdd4282009-06-12 15:20:04 -0700462 // The restore set is the concatenation of the individual record blobs,
Christopher Tateadfe8b82014-02-04 16:23:32 -0800463 // each of which is a file in the package's directory. We return the
464 // data in lexical order sorted by key, so that apps which use synthetic
465 // keys like BLOB_1, BLOB_2, etc will see the date in the most obvious
466 // order.
467 ArrayList<DecodedFilename> blobs = contentsByKey(packageDir);
Dan Egnor01445162009-09-21 17:04:05 -0700468 if (blobs == null) { // nextRestorePackage() ensures the dir exists, so this is an error
Christopher Tateadfe8b82014-02-04 16:23:32 -0800469 Log.e(TAG, "No keys for package: " + packageDir);
Christopher Tate5a009f92014-06-19 14:53:18 -0700470 return TRANSPORT_ERROR;
Christopher Tate2fdd4282009-06-12 15:20:04 -0700471 }
Dan Egnorefe52642009-06-24 00:16:33 -0700472
473 // We expect at least some data if the directory exists in the first place
Christopher Tateadfe8b82014-02-04 16:23:32 -0800474 if (DEBUG) Log.v(TAG, " getRestoreData() found " + blobs.size() + " key files");
Dan Egnorefe52642009-06-24 00:16:33 -0700475 BackupDataOutput out = new BackupDataOutput(outFd.getFileDescriptor());
476 try {
Christopher Tateadfe8b82014-02-04 16:23:32 -0800477 for (DecodedFilename keyEntry : blobs) {
478 File f = keyEntry.file;
Dan Egnorefe52642009-06-24 00:16:33 -0700479 FileInputStream in = new FileInputStream(f);
480 try {
481 int size = (int) f.length();
482 byte[] buf = new byte[size];
483 in.read(buf);
Christopher Tateadfe8b82014-02-04 16:23:32 -0800484 if (DEBUG) Log.v(TAG, " ... key=" + keyEntry.key + " size=" + size);
485 out.writeEntityHeader(keyEntry.key, size);
Dan Egnorefe52642009-06-24 00:16:33 -0700486 out.writeEntityData(buf, size);
487 } finally {
488 in.close();
489 }
490 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700491 return TRANSPORT_OK;
Dan Egnorefe52642009-06-24 00:16:33 -0700492 } catch (IOException e) {
493 Log.e(TAG, "Unable to read backup records", e);
Christopher Tate5a009f92014-06-19 14:53:18 -0700494 return TRANSPORT_ERROR;
Dan Egnorefe52642009-06-24 00:16:33 -0700495 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700496 }
Christopher Tate3a31a932009-06-22 15:10:30 -0700497
Christopher Tateadfe8b82014-02-04 16:23:32 -0800498 static class DecodedFilename implements Comparable<DecodedFilename> {
499 public File file;
500 public String key;
501
502 public DecodedFilename(File f) {
503 file = f;
504 key = new String(Base64.decode(f.getName()));
505 }
506
507 @Override
508 public int compareTo(DecodedFilename other) {
509 // sorts into ascending lexical order by decoded key
510 return key.compareTo(other.key);
511 }
512 }
513
514 // Return a list of the files in the given directory, sorted lexically by
515 // the Base64-decoded file name, not by the on-disk filename
516 private ArrayList<DecodedFilename> contentsByKey(File dir) {
517 File[] allFiles = dir.listFiles();
518 if (allFiles == null || allFiles.length == 0) {
519 return null;
520 }
521
522 // Decode the filenames into keys then sort lexically by key
523 ArrayList<DecodedFilename> contents = new ArrayList<DecodedFilename>();
524 for (File f : allFiles) {
525 contents.add(new DecodedFilename(f));
526 }
527 Collections.sort(contents);
528 return contents;
529 }
530
Christopher Tate5a009f92014-06-19 14:53:18 -0700531 @Override
Dan Egnorefe52642009-06-24 00:16:33 -0700532 public void finishRestore() {
533 if (DEBUG) Log.v(TAG, "finishRestore()");
Christopher Tate5a009f92014-06-19 14:53:18 -0700534 if (mRestoreType == RestoreDescription.TYPE_FULL_STREAM) {
535 resetFullRestoreState();
536 }
537 mRestoreType = 0;
Christopher Tate3a31a932009-06-22 15:10:30 -0700538 }
Christopher Tate9ff53a72014-06-03 17:20:07 -0700539
540 // ------------------------------------------------------------------------------------
541 // Full restore handling
542
Christopher Tate5a009f92014-06-19 14:53:18 -0700543 private void resetFullRestoreState() {
544 try {
545 mCurFullRestoreStream.close();
546 } catch (IOException e) {
547 Log.w(TAG, "Unable to close full restore input stream");
Christopher Tate9ff53a72014-06-03 17:20:07 -0700548 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700549 mCurFullRestoreStream = null;
550 mFullRestoreSocketStream = null;
551 mFullRestoreBuffer = null;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700552 }
553
554 /**
555 * Ask the transport to provide data for the "current" package being restored. The
556 * transport then writes some data to the socket supplied to this call, and returns
557 * the number of bytes written. The system will then read that many bytes and
558 * stream them to the application's agent for restore, then will call this method again
559 * to receive the next chunk of the archive. This sequence will be repeated until the
560 * transport returns zero indicating that all of the package's data has been delivered
561 * (or returns a negative value indicating some sort of hard error condition at the
562 * transport level).
563 *
564 * <p>After this method returns zero, the system will then call
565 * {@link #getNextFullRestorePackage()} to begin the restore process for the next
566 * application, and the sequence begins again.
567 *
568 * @param socket The file descriptor that the transport will use for delivering the
569 * streamed archive.
570 * @return 0 when no more data for the current package is available. A positive value
571 * indicates the presence of that much data to be delivered to the app. A negative
572 * return value is treated as equivalent to {@link BackupTransport#TRANSPORT_ERROR},
573 * indicating a fatal error condition that precludes further restore operations
574 * on the current dataset.
575 */
Christopher Tate5a009f92014-06-19 14:53:18 -0700576 @Override
Christopher Tate9ff53a72014-06-03 17:20:07 -0700577 public int getNextFullRestoreDataChunk(ParcelFileDescriptor socket) {
Christopher Tate5a009f92014-06-19 14:53:18 -0700578 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
579 throw new IllegalStateException("Asked for full restore data for non-stream package");
580 }
581
582 // first chunk?
583 if (mCurFullRestoreStream == null) {
584 final String name = mRestorePackages[mRestorePackage].packageName;
585 if (DEBUG) Log.i(TAG, "Starting full restore of " + name);
586 File dataset = new File(mRestoreSetFullDir, name);
587 try {
588 mCurFullRestoreStream = new FileInputStream(dataset);
589 } catch (IOException e) {
590 // If we can't open the target package's tarball, we return the single-package
591 // error code and let the caller go on to the next package.
592 Log.e(TAG, "Unable to read archive for " + name);
593 return TRANSPORT_PACKAGE_REJECTED;
594 }
595 mFullRestoreSocketStream = new FileOutputStream(socket.getFileDescriptor());
Christopher Tate89101f72014-07-17 19:09:00 -0700596 mFullRestoreBuffer = new byte[2*1024];
Christopher Tate5a009f92014-06-19 14:53:18 -0700597 }
598
599 int nRead;
600 try {
601 nRead = mCurFullRestoreStream.read(mFullRestoreBuffer);
602 if (nRead < 0) {
603 // EOF: tell the caller we're done
604 nRead = NO_MORE_DATA;
605 } else if (nRead == 0) {
606 // This shouldn't happen when reading a FileInputStream; we should always
607 // get either a positive nonzero byte count or -1. Log the situation and
608 // treat it as EOF.
609 Log.w(TAG, "read() of archive file returned 0; treating as EOF");
610 nRead = NO_MORE_DATA;
611 } else {
612 if (DEBUG) {
613 Log.i(TAG, " delivering restore chunk: " + nRead);
614 }
615 mFullRestoreSocketStream.write(mFullRestoreBuffer, 0, nRead);
616 }
617 } catch (IOException e) {
618 return TRANSPORT_ERROR; // Hard error accessing the file; shouldn't happen
619 } finally {
620 // Most transports will need to explicitly close 'socket' here, but this transport
621 // is in the same process as the caller so it can leave it up to the backup manager
622 // to manage both socket fds.
623 }
624
625 return nRead;
Christopher Tate9ff53a72014-06-03 17:20:07 -0700626 }
Christopher Tate5a009f92014-06-19 14:53:18 -0700627
628 /**
629 * If the OS encounters an error while processing {@link RestoreDescription#TYPE_FULL_STREAM}
630 * data for restore, it will invoke this method to tell the transport that it should
631 * abandon the data download for the current package. The OS will then either call
632 * {@link #nextRestorePackage()} again to move on to restoring the next package in the
633 * set being iterated over, or will call {@link #finishRestore()} to shut down the restore
634 * operation.
635 *
636 * @return {@link #TRANSPORT_OK} if the transport was successful in shutting down the
637 * current stream cleanly, or {@link #TRANSPORT_ERROR} to indicate a serious
638 * transport-level failure. If the transport reports an error here, the entire restore
639 * operation will immediately be finished with no further attempts to restore app data.
640 */
641 @Override
642 public int abortFullRestore() {
643 if (mRestoreType != RestoreDescription.TYPE_FULL_STREAM) {
644 throw new IllegalStateException("abortFullRestore() but not currently restoring");
645 }
646 resetFullRestoreState();
647 mRestoreType = 0;
648 return TRANSPORT_OK;
649 }
650
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700651}