LocalTransport.java revision 9679410db578e179c7559e7a52bb21c8082e9631
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.backup;
18
19import android.app.backup.BackupDataInput;
20import android.app.backup.BackupDataOutput;
21import android.app.backup.BackupTransport;
22import android.app.backup.RestoreDescription;
23import android.app.backup.RestoreSet;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.PackageInfo;
28import android.os.Environment;
29import android.os.ParcelFileDescriptor;
30import android.os.SELinux;
31import android.system.ErrnoException;
32import android.system.Os;
33import android.system.StructStat;
34import android.util.Log;
35
36import com.android.org.bouncycastle.util.encoders.Base64;
37
38import java.io.BufferedOutputStream;
39import java.io.File;
40import java.io.FileInputStream;
41import java.io.FileNotFoundException;
42import java.io.FileOutputStream;
43import java.io.IOException;
44import java.util.ArrayList;
45import java.util.Arrays;
46import java.util.Collections;
47import java.util.HashSet;
48import java.util.List;
49
50import static android.system.OsConstants.*;
51
52/**
53 * Backup transport for stashing stuff into a known location on disk, and
54 * later restoring from there.  For testing only.
55 */
56
57public class LocalTransport extends BackupTransport {
58    private static final String TAG = "LocalTransport";
59    private static final boolean DEBUG = false;
60
61    private static final String TRANSPORT_DIR_NAME
62            = "com.android.internal.backup.LocalTransport";
63
64    private static final String TRANSPORT_DESTINATION_STRING
65            = "Backing up to debug-only private cache";
66
67    private static final String TRANSPORT_DATA_MANAGEMENT_LABEL
68            = "";
69
70    private static final String INCREMENTAL_DIR = "_delta";
71    private static final String FULL_DATA_DIR = "_full";
72
73    // The currently-active restore set always has the same (nonzero!) token
74    private static final long CURRENT_SET_TOKEN = 1;
75
76    private Context mContext;
77    private File mDataDir = new File(Environment.getDownloadCacheDirectory(), "backup");
78    private File mCurrentSetDir = new File(mDataDir, Long.toString(CURRENT_SET_TOKEN));
79    private File mCurrentSetIncrementalDir = new File(mCurrentSetDir, INCREMENTAL_DIR);
80    private File mCurrentSetFullDir = new File(mCurrentSetDir, FULL_DATA_DIR);
81
82    private PackageInfo[] mRestorePackages = null;
83    private int mRestorePackage = -1;  // Index into mRestorePackages
84    private int mRestoreType;
85    private File mRestoreSetDir;
86    private File mRestoreSetIncrementalDir;
87    private File mRestoreSetFullDir;
88    private long mRestoreToken;
89
90    // 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;
99    private FileInputStream mCurFullRestoreStream;
100    private FileOutputStream mFullRestoreSocketStream;
101    private byte[] mFullRestoreBuffer;
102
103    public LocalTransport(Context context) {
104        mContext = context;
105        mCurrentSetDir.mkdirs();
106        mCurrentSetFullDir.mkdir();
107        mCurrentSetIncrementalDir.mkdir();
108        if (!SELinux.restorecon(mCurrentSetDir)) {
109            Log.e(TAG, "SELinux restorecon failed for " + mCurrentSetDir);
110        }
111    }
112
113    @Override
114    public String name() {
115        return new ComponentName(mContext, this.getClass()).flattenToShortString();
116    }
117
118    @Override
119    public Intent configurationIntent() {
120        // The local transport is not user-configurable
121        return null;
122    }
123
124    @Override
125    public String currentDestinationString() {
126        return TRANSPORT_DESTINATION_STRING;
127    }
128
129    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
140    @Override
141    public String transportDirName() {
142        return TRANSPORT_DIR_NAME;
143    }
144
145    @Override
146    public long requestBackupTime() {
147        // any time is a good time for local backup
148        return 0;
149    }
150
151    @Override
152    public int initializeDevice() {
153        if (DEBUG) Log.v(TAG, "wiping all data");
154        deleteContents(mCurrentSetDir);
155        return TRANSPORT_OK;
156    }
157
158    @Override
159    public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) {
160        if (DEBUG) {
161            try {
162            StructStat ss = Os.fstat(data.getFileDescriptor());
163            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        }
170
171        File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
172        packageDir.mkdirs();
173
174        // 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();
184                String base64Key = new String(Base64.encode(key.getBytes()));
185                File entityFile = new File(packageDir, base64Key);
186
187                int dataSize = changeSet.getDataSize();
188
189                if (DEBUG) Log.v(TAG, "Got change set key=" + key + " size=" + dataSize
190                        + " key64=" + base64Key);
191
192                if (dataSize >= 0) {
193                    if (entityFile.exists()) {
194                        entityFile.delete();
195                    }
196                    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);
203                    if (DEBUG) {
204                        try {
205                            long cur = Os.lseek(data.getFileDescriptor(), 0, SEEK_CUR);
206                            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                    }
213
214                    try {
215                        entity.write(buf, 0, dataSize);
216                    } catch (IOException e) {
217                        Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath());
218                        return TRANSPORT_ERROR;
219                    } finally {
220                        entity.close();
221                    }
222                } else {
223                    entityFile.delete();
224                }
225            }
226            return TRANSPORT_OK;
227        } catch (IOException e) {
228            // oops, something went wrong.  abort the operation and return error.
229            Log.v(TAG, "Exception reading backup input:", e);
230            return TRANSPORT_ERROR;
231        }
232    }
233
234    // 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
249    @Override
250    public int clearBackupData(PackageInfo packageInfo) {
251        if (DEBUG) Log.v(TAG, "clearBackupData() pkg=" + packageInfo.packageName);
252
253        File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
254        final File[] fileset = packageDir.listFiles();
255        if (fileset != null) {
256            for (File f : fileset) {
257                f.delete();
258            }
259            packageDir.delete();
260        }
261
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
271        return TRANSPORT_OK;
272    }
273
274    @Override
275    public int finishBackup() {
276        if (DEBUG) Log.v(TAG, "finishBackup()");
277        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) {
288                if (DEBUG) {
289                    Log.w(TAG, "Exception caught in finishBackup()", e);
290                }
291                return TRANSPORT_ERROR;
292            } finally {
293                mSocket = null;
294            }
295        }
296        return TRANSPORT_OK;
297    }
298
299    // ------------------------------------------------------------------------------------
300    // Full backup handling
301
302    @Override
303    public long requestFullBackupTime() {
304        return 0;
305    }
306
307    @Override
308    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");
311            return TRANSPORT_ERROR;
312        }
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");
326            return TRANSPORT_ERROR;
327        }
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) {
335            return TRANSPORT_ERROR;
336        }
337        mFullBackupOutputStream = new BufferedOutputStream(tarstream);
338        mFullBackupBuffer = new byte[4096];
339
340        return TRANSPORT_OK;
341    }
342
343    @Override
344    public int sendBackupData(int numBytes) {
345        if (mFullBackupBuffer == null) {
346            Log.w(TAG, "Attempted sendBackupData before performFullBackup");
347            return TRANSPORT_ERROR;
348        }
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");
359                return TRANSPORT_ERROR;
360            }
361            mFullBackupOutputStream.write(mFullBackupBuffer, 0, nRead);
362            numBytes -= nRead;
363            } catch (IOException e) {
364                Log.e(TAG, "Error handling backup data for " + mFullTargetPackage);
365                return TRANSPORT_ERROR;
366            }
367        }
368        return TRANSPORT_OK;
369    }
370
371    // ------------------------------------------------------------------------------------
372    // Restore handling
373    static final long[] POSSIBLE_SETS = { 2, 3, 4, 5, 6, 7, 8, 9 };
374
375    @Override
376    public RestoreSet[] getAvailableRestoreSets() {
377        long[] existing = new long[POSSIBLE_SETS.length + 1];
378        int num = 0;
379
380        // see which possible non-current sets exist...
381        for (long token : POSSIBLE_SETS) {
382            if ((new File(mDataDir, Long.toString(token))).exists()) {
383                existing[num++] = token;
384            }
385        }
386        // ...and always the currently-active set last
387        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;
394    }
395
396    @Override
397    public long getCurrentRestoreSet() {
398        // The current restore set always has the same token
399        return CURRENT_SET_TOKEN;
400    }
401
402    @Override
403    public int startRestore(long token, PackageInfo[] packages) {
404        if (DEBUG) Log.v(TAG, "start restore " + token + " : " + packages.length
405                + " matching packages");
406        mRestorePackages = packages;
407        mRestorePackage = -1;
408        mRestoreToken = token;
409        mRestoreSetDir = new File(mDataDir, Long.toString(token));
410        mRestoreSetIncrementalDir = new File(mRestoreSetDir, INCREMENTAL_DIR);
411        mRestoreSetFullDir = new File(mRestoreSetDir, FULL_DATA_DIR);
412        return TRANSPORT_OK;
413    }
414
415    @Override
416    public RestoreDescription nextRestorePackage() {
417        if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
418
419        boolean found = false;
420        while (++mRestorePackage < mRestorePackages.length) {
421            String name = mRestorePackages[mRestorePackage].packageName;
422
423            // If we have key/value data for this package, deliver that
424            // skip packages where we have a data dir but no actual contents
425            String[] contents = (new File(mRestoreSetIncrementalDir, name)).list();
426            if (contents != null && contents.length > 0) {
427                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;
438                    mCurFullRestoreStream = null;   // ensure starting from the ground state
439                    found = true;
440                }
441            }
442
443            if (found) {
444                return new RestoreDescription(name, mRestoreType);
445            }
446        }
447
448        if (DEBUG) Log.v(TAG, "  no more packages to restore");
449        return RestoreDescription.NO_MORE_PACKAGES;
450    }
451
452    @Override
453    public int getRestoreData(ParcelFileDescriptor outFd) {
454        if (mRestorePackages == null) throw new IllegalStateException("startRestore not called");
455        if (mRestorePackage < 0) throw new IllegalStateException("nextRestorePackage not called");
456        if (mRestoreType != RestoreDescription.TYPE_KEY_VALUE) {
457            throw new IllegalStateException("getRestoreData(fd) for non-key/value dataset");
458        }
459        File packageDir = new File(mRestoreSetIncrementalDir,
460                mRestorePackages[mRestorePackage].packageName);
461
462        // The restore set is the concatenation of the individual record blobs,
463        // 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);
468        if (blobs == null) {  // nextRestorePackage() ensures the dir exists, so this is an error
469            Log.e(TAG, "No keys for package: " + packageDir);
470            return TRANSPORT_ERROR;
471        }
472
473        // We expect at least some data if the directory exists in the first place
474        if (DEBUG) Log.v(TAG, "  getRestoreData() found " + blobs.size() + " key files");
475        BackupDataOutput out = new BackupDataOutput(outFd.getFileDescriptor());
476        try {
477            for (DecodedFilename keyEntry : blobs) {
478                File f = keyEntry.file;
479                FileInputStream in = new FileInputStream(f);
480                try {
481                    int size = (int) f.length();
482                    byte[] buf = new byte[size];
483                    in.read(buf);
484                    if (DEBUG) Log.v(TAG, "    ... key=" + keyEntry.key + " size=" + size);
485                    out.writeEntityHeader(keyEntry.key, size);
486                    out.writeEntityData(buf, size);
487                } finally {
488                    in.close();
489                }
490            }
491            return TRANSPORT_OK;
492        } catch (IOException e) {
493            Log.e(TAG, "Unable to read backup records", e);
494            return TRANSPORT_ERROR;
495        }
496    }
497
498    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
531    @Override
532    public void finishRestore() {
533        if (DEBUG) Log.v(TAG, "finishRestore()");
534        if (mRestoreType == RestoreDescription.TYPE_FULL_STREAM) {
535            resetFullRestoreState();
536        }
537        mRestoreType = 0;
538    }
539
540    // ------------------------------------------------------------------------------------
541    // Full restore handling
542
543    private void resetFullRestoreState() {
544        try {
545        mCurFullRestoreStream.close();
546        } catch (IOException e) {
547            Log.w(TAG, "Unable to close full restore input stream");
548        }
549        mCurFullRestoreStream = null;
550        mFullRestoreSocketStream = null;
551        mFullRestoreBuffer = null;
552    }
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     */
576    @Override
577    public int getNextFullRestoreDataChunk(ParcelFileDescriptor socket) {
578        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());
596            mFullRestoreBuffer = new byte[2*1024];
597        }
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;
626    }
627
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
651}
652