BackupManagerService.java revision cde87f45e0fa052d070b88ae33fb03c89870536a
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.server;
18
19import android.app.ActivityManagerNative;
20import android.app.IActivityManager;
21import android.app.IApplicationThread;
22import android.app.IBackupAgent;
23import android.content.BroadcastReceiver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.IPackageDataObserver;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.net.Uri;
33import android.os.Binder;
34import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.IBinder;
38import android.os.Message;
39import android.os.ParcelFileDescriptor;
40import android.os.Process;
41import android.os.RemoteException;
42import android.util.Log;
43import android.util.SparseArray;
44
45import android.backup.IBackupManager;
46import android.backup.IRestoreSession;
47import android.backup.BackupManager;
48import android.backup.RestoreSet;
49
50import com.android.internal.backup.LocalTransport;
51import com.android.internal.backup.GoogleTransport;
52import com.android.internal.backup.IBackupTransport;
53
54import java.io.EOFException;
55import java.io.File;
56import java.io.FileDescriptor;
57import java.io.FileNotFoundException;
58import java.io.IOException;
59import java.io.PrintWriter;
60import java.io.RandomAccessFile;
61import java.lang.String;
62import java.util.ArrayList;
63import java.util.HashMap;
64import java.util.HashSet;
65import java.util.Iterator;
66import java.util.List;
67
68class BackupManagerService extends IBackupManager.Stub {
69    private static final String TAG = "BackupManagerService";
70    private static final boolean DEBUG = true;
71
72    private static final long COLLECTION_INTERVAL = 1000;
73    //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
74
75    private static final int MSG_RUN_BACKUP = 1;
76    private static final int MSG_RUN_FULL_BACKUP = 2;
77    private static final int MSG_RUN_RESTORE = 3;
78
79    // Timeout interval for deciding that a bind or clear-data has taken too long
80    static final long TIMEOUT_INTERVAL = 10 * 1000;
81
82    private Context mContext;
83    private PackageManager mPackageManager;
84    private final IActivityManager mActivityManager;
85    private final BackupHandler mBackupHandler = new BackupHandler();
86    // map UIDs to the set of backup client services within that UID's app set
87    private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
88        = new SparseArray<HashSet<ApplicationInfo>>();
89    // set of backup services that have pending changes
90    private class BackupRequest {
91        public ApplicationInfo appInfo;
92        public boolean fullBackup;
93
94        BackupRequest(ApplicationInfo app, boolean isFull) {
95            appInfo = app;
96            fullBackup = isFull;
97        }
98
99        public String toString() {
100            return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
101        }
102    }
103    // Backups that we haven't started yet.
104    private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
105            = new HashMap<ApplicationInfo,BackupRequest>();
106    // Backups that we have started.  These are separate to prevent starvation
107    // if an app keeps re-enqueuing itself.
108    private ArrayList<BackupRequest> mBackupQueue;
109    private final Object mQueueLock = new Object();
110
111    // The thread performing the sequence of queued backups binds to each app's agent
112    // in succession.  Bind notifications are asynchronously delivered through the
113    // Activity Manager; use this lock object to signal when a requested binding has
114    // completed.
115    private final Object mAgentConnectLock = new Object();
116    private IBackupAgent mConnectedAgent;
117    private volatile boolean mConnecting;
118
119    // A similar synchronicity mechanism around clearing apps' data for restore
120    private final Object mClearDataLock = new Object();
121    private volatile boolean mClearingData;
122
123    private int mTransportId;
124
125    private File mStateDir;
126    private File mDataDir;
127    private File mJournalDir;
128    private File mJournal;
129    private RandomAccessFile mJournalStream;
130
131    public BackupManagerService(Context context) {
132        mContext = context;
133        mPackageManager = context.getPackageManager();
134        mActivityManager = ActivityManagerNative.getDefault();
135
136        // Set up our bookkeeping
137        mStateDir = new File(Environment.getDataDirectory(), "backup");
138        mStateDir.mkdirs();
139        mDataDir = Environment.getDownloadCacheDirectory();
140
141        // Set up the backup-request journaling
142        mJournalDir = new File(mStateDir, "pending");
143        mJournalDir.mkdirs();
144        makeJournalLocked();    // okay because no other threads are running yet
145
146        //!!! TODO: default to cloud transport, not local
147        mTransportId = BackupManager.TRANSPORT_LOCAL;
148
149        // Build our mapping of uid to backup client services
150        synchronized (mBackupParticipants) {
151            addPackageParticipantsLocked(null);
152        }
153
154        // Now that we know about valid backup participants, parse any
155        // leftover journal files and schedule a new backup pass
156        parseLeftoverJournals();
157
158        // Register for broadcasts about package install, etc., so we can
159        // update the provider list.
160        IntentFilter filter = new IntentFilter();
161        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
162        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
163        filter.addDataScheme("package");
164        mContext.registerReceiver(mBroadcastReceiver, filter);
165    }
166
167    private void makeJournalLocked() {
168        try {
169            mJournal = File.createTempFile("journal", null, mJournalDir);
170            mJournalStream = new RandomAccessFile(mJournal, "rwd");
171        } catch (IOException e) {
172            Log.e(TAG, "Unable to write backup journals");
173            mJournal = null;
174            mJournalStream = null;
175        }
176    }
177
178    private void parseLeftoverJournals() {
179        if (mJournal != null) {
180            File[] allJournals = mJournalDir.listFiles();
181            for (File f : allJournals) {
182                if (f.compareTo(mJournal) != 0) {
183                    // This isn't the current journal, so it must be a leftover.  Read
184                    // out the package names mentioned there and schedule them for
185                    // backup.
186                    try {
187                        Log.i(TAG, "Found stale backup journal, scheduling:");
188                        RandomAccessFile in = new RandomAccessFile(f, "r");
189                        while (true) {
190                            String packageName = in.readUTF();
191                            Log.i(TAG, "    + " + packageName);
192                            dataChanged(packageName);
193                        }
194                    } catch (EOFException e) {
195                        // no more data; we're done
196                    } catch (Exception e) {
197                        // can't read it or other error; just skip it
198                    } finally {
199                        // close/delete the file
200                        f.delete();
201                    }
202                }
203            }
204        }
205    }
206
207    // ----- Track installation/removal of packages -----
208    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
209        public void onReceive(Context context, Intent intent) {
210            if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
211
212            Uri uri = intent.getData();
213            if (uri == null) {
214                return;
215            }
216            String pkgName = uri.getSchemeSpecificPart();
217            if (pkgName == null) {
218                return;
219            }
220
221            String action = intent.getAction();
222            if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
223                synchronized (mBackupParticipants) {
224                    Bundle extras = intent.getExtras();
225                    if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
226                        // The package was just upgraded
227                        updatePackageParticipantsLocked(pkgName);
228                    } else {
229                        // The package was just added
230                        addPackageParticipantsLocked(pkgName);
231                    }
232                }
233            }
234            else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
235                Bundle extras = intent.getExtras();
236                if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
237                    // The package is being updated.  We'll receive a PACKAGE_ADDED shortly.
238                } else {
239                    synchronized (mBackupParticipants) {
240                        removePackageParticipantsLocked(pkgName);
241                    }
242                }
243            }
244        }
245    };
246
247    // ----- Run the actual backup process asynchronously -----
248
249    private class BackupHandler extends Handler {
250        public void handleMessage(Message msg) {
251
252            switch (msg.what) {
253            case MSG_RUN_BACKUP:
254                // snapshot the pending-backup set and work on that
255                File oldJournal = mJournal;
256                RandomAccessFile oldJournalStream = mJournalStream;
257                synchronized (mQueueLock) {
258                    if (mBackupQueue == null) {
259                        mBackupQueue = new ArrayList<BackupRequest>();
260                        for (BackupRequest b: mPendingBackups.values()) {
261                            mBackupQueue.add(b);
262                        }
263                        mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
264                    }
265                    // !!! TODO: start a new backup-queue journal file too
266                    if (mJournalStream != null) {
267                        try {
268                            mJournalStream.close();
269                        } catch (IOException e) {
270                            // don't need to do anything
271                        }
272                        makeJournalLocked();
273                    }
274
275                    // At this point, we have started a new journal file, and the old
276                    // file identity is being passed to the backup processing thread.
277                    // When it completes successfully, that old journal file will be
278                    // deleted.  If we crash prior to that, the old journal is parsed
279                    // at next boot and the journaled requests fulfilled.
280                }
281                (new PerformBackupThread(mTransportId, mBackupQueue, oldJournal)).run();
282                break;
283
284            case MSG_RUN_FULL_BACKUP:
285                break;
286
287            case MSG_RUN_RESTORE:
288            {
289                int token = msg.arg1;
290                IBackupTransport transport = (IBackupTransport)msg.obj;
291                (new PerformRestoreThread(transport, token)).run();
292                break;
293            }
294            }
295        }
296    }
297
298    // Add the backup agents in the given package to our set of known backup participants.
299    // If 'packageName' is null, adds all backup agents in the whole system.
300    void addPackageParticipantsLocked(String packageName) {
301        // Look for apps that define the android:backupAgent attribute
302        if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
303        List<ApplicationInfo> targetApps = allAgentApps();
304        addPackageParticipantsLockedInner(packageName, targetApps);
305    }
306
307    private void addPackageParticipantsLockedInner(String packageName,
308            List<ApplicationInfo> targetApps) {
309        if (DEBUG) {
310            Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
311            for (ApplicationInfo a : targetApps) {
312                Log.v(TAG, "    " + a + " agent=" + a.backupAgentName);
313            }
314        }
315
316        for (ApplicationInfo app : targetApps) {
317            if (packageName == null || app.packageName.equals(packageName)) {
318                int uid = app.uid;
319                HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
320                if (set == null) {
321                    set = new HashSet<ApplicationInfo>();
322                    mBackupParticipants.put(uid, set);
323                }
324                set.add(app);
325            }
326        }
327    }
328
329    // Remove the given package's backup services from our known active set.  If
330    // 'packageName' is null, *all* backup services will be removed.
331    void removePackageParticipantsLocked(String packageName) {
332        if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
333        List<ApplicationInfo> allApps = null;
334        if (packageName != null) {
335            allApps = new ArrayList<ApplicationInfo>();
336            try {
337                ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
338                allApps.add(app);
339            } catch (Exception e) {
340                // just skip it
341            }
342        } else {
343            // all apps with agents
344            allApps = allAgentApps();
345        }
346        removePackageParticipantsLockedInner(packageName, allApps);
347    }
348
349    private void removePackageParticipantsLockedInner(String packageName,
350            List<ApplicationInfo> agents) {
351        if (DEBUG) {
352            Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
353                    + ") removing " + agents.size() + " entries");
354            for (ApplicationInfo a : agents) {
355                Log.v(TAG, "    - " + a);
356            }
357        }
358        for (ApplicationInfo app : agents) {
359            if (packageName == null || app.packageName.equals(packageName)) {
360                int uid = app.uid;
361                HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
362                if (set != null) {
363                    // Find the existing entry with the same package name, and remove it.
364                    // We can't just remove(app) because the instances are different.
365                    for (ApplicationInfo entry: set) {
366                        if (entry.packageName.equals(app.packageName)) {
367                            set.remove(entry);
368                            break;
369                        }
370                    }
371                    if (set.size() == 0) {
372                        mBackupParticipants.delete(uid);                    }
373                }
374            }
375        }
376    }
377
378    // Returns the set of all applications that define an android:backupAgent attribute
379    private List<ApplicationInfo> allAgentApps() {
380        List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
381        int N = allApps.size();
382        if (N > 0) {
383            for (int a = N-1; a >= 0; a--) {
384                ApplicationInfo app = allApps.get(a);
385                if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
386                        || app.backupAgentName == null) {
387                    allApps.remove(a);
388                }
389            }
390        }
391        return allApps;
392    }
393
394    // Reset the given package's known backup participants.  Unlike add/remove, the update
395    // action cannot be passed a null package name.
396    void updatePackageParticipantsLocked(String packageName) {
397        if (packageName == null) {
398            Log.e(TAG, "updatePackageParticipants called with null package name");
399            return;
400        }
401        if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
402
403        // brute force but small code size
404        List<ApplicationInfo> allApps = allAgentApps();
405        removePackageParticipantsLockedInner(packageName, allApps);
406        addPackageParticipantsLockedInner(packageName, allApps);
407    }
408
409    // Instantiate the given transport
410    private IBackupTransport createTransport(int transportID) {
411        IBackupTransport transport = null;
412        switch (transportID) {
413        case BackupManager.TRANSPORT_LOCAL:
414            if (DEBUG) Log.v(TAG, "Initializing local transport");
415            transport = new LocalTransport(mContext);
416            break;
417
418        case BackupManager.TRANSPORT_GOOGLE:
419            if (DEBUG) Log.v(TAG, "Initializing Google transport");
420            //!!! TODO: stand up the google backup transport for real here
421            transport = new GoogleTransport();
422            break;
423
424        default:
425            Log.e(TAG, "creating unknown transport " + transportID);
426        }
427        return transport;
428    }
429
430    // fire off a backup agent, blocking until it attaches or times out
431    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
432        IBackupAgent agent = null;
433        synchronized(mAgentConnectLock) {
434            mConnecting = true;
435            mConnectedAgent = null;
436            try {
437                if (mActivityManager.bindBackupAgent(app, mode)) {
438                    Log.d(TAG, "awaiting agent for " + app);
439
440                    // success; wait for the agent to arrive
441                    // only wait 10 seconds for the clear data to happen
442                    long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
443                    while (mConnecting && mConnectedAgent == null
444                            && (System.currentTimeMillis() < timeoutMark)) {
445                        try {
446                            mAgentConnectLock.wait(5000);
447                        } catch (InterruptedException e) {
448                            // just bail
449                            return null;
450                        }
451                    }
452
453                    // if we timed out with no connect, abort and move on
454                    if (mConnecting == true) {
455                        Log.w(TAG, "Timeout waiting for agent " + app);
456                        return null;
457                    }
458                    agent = mConnectedAgent;
459                }
460            } catch (RemoteException e) {
461                // can't happen
462            }
463        }
464        return agent;
465    }
466
467    // clear an application's data, blocking until the operation completes or times out
468    void clearApplicationDataSynchronous(String packageName) {
469        ClearDataObserver observer = new ClearDataObserver();
470
471        synchronized(mClearDataLock) {
472            mClearingData = true;
473            mPackageManager.clearApplicationUserData(packageName, observer);
474
475            // only wait 10 seconds for the clear data to happen
476            long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
477            while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
478                try {
479                    mClearDataLock.wait(5000);
480                } catch (InterruptedException e) {
481                    // won't happen, but still.
482                    mClearingData = false;
483                }
484            }
485        }
486    }
487
488    class ClearDataObserver extends IPackageDataObserver.Stub {
489        public void onRemoveCompleted(String packageName, boolean succeeded)
490                throws android.os.RemoteException {
491            synchronized(mClearDataLock) {
492                mClearingData = false;
493                notifyAll();
494            }
495        }
496    }
497
498    // ----- Back up a set of applications via a worker thread -----
499
500    class PerformBackupThread extends Thread {
501        private static final String TAG = "PerformBackupThread";
502        int mTransport;
503        ArrayList<BackupRequest> mQueue;
504        File mJournal;
505
506        public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue,
507                File journal) {
508            mTransport = transportId;
509            mQueue = queue;
510            mJournal = journal;
511        }
512
513        @Override
514        public void run() {
515            if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
516
517            // stand up the current transport
518            IBackupTransport transport = createTransport(mTransport);
519            if (transport == null) {
520                return;
521            }
522
523            // start up the transport
524            try {
525                transport.startSession();
526            } catch (Exception e) {
527                Log.e(TAG, "Error session transport");
528                e.printStackTrace();
529                return;
530            }
531
532            // The transport is up and running; now run all the backups in our queue
533            doQueuedBackups(transport);
534
535            // Finally, tear down the transport
536            try {
537                transport.endSession();
538            } catch (Exception e) {
539                Log.e(TAG, "Error ending transport");
540                e.printStackTrace();
541            }
542
543            if (!mJournal.delete()) {
544                Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
545            }
546        }
547
548        private void doQueuedBackups(IBackupTransport transport) {
549            for (BackupRequest request : mQueue) {
550                Log.d(TAG, "starting agent for backup of " + request);
551
552                IBackupAgent agent = null;
553                int mode = (request.fullBackup)
554                        ? IApplicationThread.BACKUP_MODE_FULL
555                        : IApplicationThread.BACKUP_MODE_INCREMENTAL;
556                try {
557                    agent = bindToAgentSynchronous(request.appInfo, mode);
558                    if (agent != null) {
559                        processOneBackup(request, agent, transport);
560                    }
561
562                    // unbind even on timeout, just in case
563                    mActivityManager.unbindBackupAgent(request.appInfo);
564                } catch (SecurityException ex) {
565                    // Try for the next one.
566                    Log.d(TAG, "error in bind/backup", ex);
567                } catch (RemoteException e) {
568                    Log.v(TAG, "bind/backup threw");
569                    e.printStackTrace();
570                }
571
572            }
573        }
574
575        void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
576            final String packageName = request.appInfo.packageName;
577            Log.d(TAG, "processOneBackup doBackup() on " + packageName);
578
579            try {
580                // Look up the package info & signatures.  This is first so that if it
581                // throws an exception, there's no file setup yet that would need to
582                // be unraveled.
583                PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
584                        PackageManager.GET_SIGNATURES);
585
586                // !!! TODO: get the state file dir from the transport
587                File savedStateName = new File(mStateDir, packageName);
588                File backupDataName = new File(mDataDir, packageName + ".data");
589                File newStateName = new File(mStateDir, packageName + ".new");
590
591                // In a full backup, we pass a null ParcelFileDescriptor as
592                // the saved-state "file"
593                ParcelFileDescriptor savedState = (request.fullBackup) ? null
594                        : ParcelFileDescriptor.open(savedStateName,
595                            ParcelFileDescriptor.MODE_READ_ONLY |
596                            ParcelFileDescriptor.MODE_CREATE);
597
598                backupDataName.delete();
599                ParcelFileDescriptor backupData =
600                        ParcelFileDescriptor.open(backupDataName,
601                                ParcelFileDescriptor.MODE_READ_WRITE |
602                                ParcelFileDescriptor.MODE_CREATE);
603
604                newStateName.delete();
605                ParcelFileDescriptor newState =
606                        ParcelFileDescriptor.open(newStateName,
607                                ParcelFileDescriptor.MODE_READ_WRITE |
608                                ParcelFileDescriptor.MODE_CREATE);
609
610                // Run the target's backup pass
611                boolean success = false;
612                try {
613                    agent.doBackup(savedState, backupData, newState);
614                    success = true;
615                } finally {
616                    if (savedState != null) {
617                        savedState.close();
618                    }
619                    backupData.close();
620                    newState.close();
621                }
622
623                // Now propagate the newly-backed-up data to the transport
624                if (success) {
625                    if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
626                    backupData =
627                        ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
628                    int error = transport.performBackup(packInfo, backupData);
629
630                    // !!! TODO: After successful transport, delete the now-stale data
631                    // and juggle the files so that next time the new state is passed
632                    //backupDataName.delete();
633                    newStateName.renameTo(savedStateName);
634                }
635            } catch (NameNotFoundException e) {
636                Log.e(TAG, "Package not found on backup: " + packageName);
637            } catch (FileNotFoundException fnf) {
638                Log.w(TAG, "File not found on backup: ");
639                fnf.printStackTrace();
640            } catch (RemoteException e) {
641                Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
642                e.printStackTrace();
643            } catch (Exception e) {
644                Log.w(TAG, "Final exception guard in backup: ");
645                e.printStackTrace();
646            }
647        }
648    }
649
650
651    // ----- Restore handling -----
652
653    // Is the given package restorable on this device?  Returns the on-device app's
654    // ApplicationInfo struct if it is; null if not.
655    //
656    // !!! TODO: also consider signatures
657    PackageInfo isRestorable(PackageInfo packageInfo) {
658        if (packageInfo.packageName != null) {
659            try {
660                PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
661                        PackageManager.GET_SIGNATURES);
662                if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
663                    return app;
664                }
665            } catch (Exception e) {
666                // doesn't exist on this device, or other error -- just ignore it.
667            }
668        }
669        return null;
670    }
671
672    class PerformRestoreThread extends Thread {
673        private IBackupTransport mTransport;
674        private int mToken;
675        private RestoreSet mImage;
676
677        PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
678            mTransport = transport;
679            mToken = restoreSetToken;
680        }
681
682        @Override
683        public void run() {
684            /**
685             * Restore sequence:
686             *
687             * 1. start up the transport session
688             * 2. get the restore set description for our identity
689             * 3. for each app in the restore set:
690             *    3.a. if it's restorable on this device, add it to the restore queue
691             * 4. for each app in the restore queue:
692             *    4.a. clear the app data
693             *    4.b. get the restore data for the app from the transport
694             *    4.c. launch the backup agent for the app
695             *    4.d. agent.doRestore() with the data from the server
696             *    4.e. unbind the agent [and kill the app?]
697             * 5. shut down the transport
698             */
699
700            int err = -1;
701            try {
702                err = mTransport.startSession();
703            } catch (Exception e) {
704                Log.e(TAG, "Error starting transport for restore");
705                e.printStackTrace();
706            }
707
708            if (err == 0) {
709                // build the set of apps to restore
710                try {
711                    RestoreSet[] images = mTransport.getAvailableRestoreSets();
712                    if (images.length > 0) {
713                        // !!! TODO: pick out the set for this token
714                        mImage = images[0];
715
716                        // build the set of apps we will attempt to restore
717                        PackageInfo[] packages = mTransport.getAppSet(mImage.token);
718                        HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
719                        for (PackageInfo pkg: packages) {
720                            // get the real PackageManager idea of the package
721                            PackageInfo app = isRestorable(pkg);
722                            if (app != null) {
723                                appsToRestore.add(app);
724                            }
725                        }
726
727                        // now run the restore queue
728                        doQueuedRestores(appsToRestore);
729                    }
730                } catch (RemoteException e) {
731                    // can't happen; transports run locally
732                }
733
734                // done; shut down the transport
735                try {
736                    mTransport.endSession();
737                } catch (Exception e) {
738                    Log.e(TAG, "Error ending transport for restore");
739                    e.printStackTrace();
740                }
741            }
742
743            // even if the initial session startup failed, report that we're done here
744        }
745
746        // restore each app in the queue
747        void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
748            for (PackageInfo app : appsToRestore) {
749                Log.d(TAG, "starting agent for restore of " + app);
750
751                try {
752                    // Remove the app's data first
753                    clearApplicationDataSynchronous(app.packageName);
754
755                    // Now perform the restore into the clean app
756                    IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
757                            IApplicationThread.BACKUP_MODE_RESTORE);
758                    if (agent != null) {
759                        processOneRestore(app, agent);
760                    }
761
762                    // unbind even on timeout, just in case
763                    mActivityManager.unbindBackupAgent(app.applicationInfo);
764                } catch (SecurityException ex) {
765                    // Try for the next one.
766                    Log.d(TAG, "error in bind", ex);
767                } catch (RemoteException e) {
768                    // can't happen
769                }
770
771            }
772        }
773
774        // Do the guts of a restore of one application, derived from the 'mImage'
775        // restore set via the 'mTransport' transport.
776        void processOneRestore(PackageInfo app, IBackupAgent agent) {
777            // !!! TODO: actually run the restore through mTransport
778            final String packageName = app.packageName;
779
780            // !!! TODO: get the dirs from the transport
781            File backupDataName = new File(mDataDir, packageName + ".restore");
782            backupDataName.delete();
783            try {
784                ParcelFileDescriptor backupData =
785                    ParcelFileDescriptor.open(backupDataName,
786                            ParcelFileDescriptor.MODE_READ_WRITE |
787                            ParcelFileDescriptor.MODE_CREATE);
788
789                // Run the transport's restore pass
790                // Run the target's backup pass
791                int err = -1;
792                try {
793                    err = mTransport.getRestoreData(mImage.token, app, backupData);
794                } catch (RemoteException e) {
795                    // can't happen
796                } finally {
797                    backupData.close();
798                }
799
800                // Okay, we have the data.  Now have the agent do the restore.
801                File newStateName = new File(mStateDir, packageName + ".new");
802                ParcelFileDescriptor newState =
803                    ParcelFileDescriptor.open(newStateName,
804                            ParcelFileDescriptor.MODE_READ_WRITE |
805                            ParcelFileDescriptor.MODE_CREATE);
806
807                backupData = ParcelFileDescriptor.open(backupDataName,
808                            ParcelFileDescriptor.MODE_READ_ONLY);
809
810                boolean success = false;
811                try {
812                    agent.doRestore(backupData, newState);
813                    success = true;
814                } catch (Exception e) {
815                    Log.e(TAG, "Restore failed for " + packageName);
816                    e.printStackTrace();
817                } finally {
818                    newState.close();
819                    backupData.close();
820                }
821
822                // if everything went okay, remember the recorded state now
823                if (success) {
824                    File savedStateName = new File(mStateDir, packageName);
825                    newStateName.renameTo(savedStateName);
826                }
827            } catch (FileNotFoundException fnfe) {
828                Log.v(TAG, "Couldn't open file for restore: " + fnfe);
829            } catch (IOException ioe) {
830                Log.e(TAG, "Unable to process restore file: " + ioe);
831            } catch (Exception e) {
832                Log.e(TAG, "Final exception guard in restore:");
833                e.printStackTrace();
834            }
835        }
836    }
837
838
839    // ----- IBackupManager binder interface -----
840
841    public void dataChanged(String packageName) throws RemoteException {
842        // Record that we need a backup pass for the caller.  Since multiple callers
843        // may share a uid, we need to note all candidates within that uid and schedule
844        // a backup pass for each of them.
845
846        Log.d(TAG, "dataChanged packageName=" + packageName);
847
848        HashSet<ApplicationInfo> targets = mBackupParticipants.get(Binder.getCallingUid());
849        if (targets != null) {
850            synchronized (mQueueLock) {
851                // Note that this client has made data changes that need to be backed up
852                for (ApplicationInfo app : targets) {
853                    // validate the caller-supplied package name against the known set of
854                    // packages associated with this uid
855                    if (app.packageName.equals(packageName)) {
856                        // Add the caller to the set of pending backups.  If there is
857                        // one already there, then overwrite it, but no harm done.
858                        BackupRequest req = new BackupRequest(app, false);
859                        mPendingBackups.put(app, req);
860
861                        // Journal this request in case of crash
862                        writeToJournalLocked(packageName);
863                    }
864                }
865
866                if (DEBUG) {
867                    int numKeys = mPendingBackups.size();
868                    Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
869                    for (BackupRequest b : mPendingBackups.values()) {
870                        Log.d(TAG, "    + " + b + " agent=" + b.appInfo.backupAgentName);
871                    }
872                }
873                // Schedule a backup pass in a few minutes.  As backup-eligible data
874                // keeps changing, continue to defer the backup pass until things
875                // settle down, to avoid extra overhead.
876                mBackupHandler.removeMessages(MSG_RUN_BACKUP);
877                mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
878            }
879        } else {
880            Log.w(TAG, "dataChanged but no participant pkg " + packageName);
881        }
882    }
883
884    private void writeToJournalLocked(String str) {
885        if (mJournalStream != null) {
886            try {
887                mJournalStream.writeUTF(str);
888            } catch (IOException e) {
889                Log.e(TAG, "Error writing to backup journal");
890                mJournalStream = null;
891                mJournal = null;
892            }
893        }
894    }
895
896    // Schedule a backup pass for a given package.  This method will schedule a
897    // full backup even for apps that do not declare an android:backupAgent, so
898    // use with care.
899    public void scheduleFullBackup(String packageName) throws RemoteException {
900        mContext.enforceCallingPermission("android.permission.BACKUP", "scheduleFullBackup");
901
902        if (DEBUG) Log.v(TAG, "Scheduling immediate full backup for " + packageName);
903        synchronized (mQueueLock) {
904            try {
905                ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
906                mPendingBackups.put(app, new BackupRequest(app, true));
907                mBackupHandler.sendEmptyMessage(MSG_RUN_FULL_BACKUP);
908            } catch (NameNotFoundException e) {
909                Log.w(TAG, "Could not find app for " + packageName + " to schedule full backup");
910            }
911        }
912    }
913
914    // Select which transport to use for the next backup operation
915    public int selectBackupTransport(int transportId) {
916        mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
917
918        int prevTransport = mTransportId;
919        mTransportId = transportId;
920        return prevTransport;
921    }
922
923    // Callback: a requested backup agent has been instantiated.  This should only
924    // be called from the Activity Manager.
925    public void agentConnected(String packageName, IBinder agentBinder) {
926        synchronized(mAgentConnectLock) {
927            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
928                Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
929                IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
930                mConnectedAgent = agent;
931                mConnecting = false;
932            } else {
933                Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
934                        + " claiming agent connected");
935            }
936            mAgentConnectLock.notifyAll();
937        }
938    }
939
940    // Callback: a backup agent has failed to come up, or has unexpectedly quit.
941    // If the agent failed to come up in the first place, the agentBinder argument
942    // will be null.  This should only be called from the Activity Manager.
943    public void agentDisconnected(String packageName) {
944        // TODO: handle backup being interrupted
945        synchronized(mAgentConnectLock) {
946            if (Binder.getCallingUid() == Process.SYSTEM_UID) {
947                mConnectedAgent = null;
948                mConnecting = false;
949            } else {
950                Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
951                        + " claiming agent disconnected");
952            }
953            mAgentConnectLock.notifyAll();
954        }
955    }
956
957    // Hand off a restore session
958    public IRestoreSession beginRestoreSession(int transportID) {
959        mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
960        return null;
961    }
962
963    // ----- Restore session -----
964
965    class RestoreSession extends IRestoreSession.Stub {
966        private IBackupTransport mRestoreTransport = null;
967        RestoreSet[] mRestoreSets = null;
968
969        RestoreSession(int transportID) {
970            mRestoreTransport = createTransport(transportID);
971        }
972
973        // --- Binder interface ---
974        public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
975            mContext.enforceCallingPermission("android.permission.BACKUP",
976                    "getAvailableRestoreSets");
977
978            synchronized(this) {
979                if (mRestoreSets == null) {
980                    mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
981                }
982                return mRestoreSets;
983            }
984        }
985
986        public int performRestore(int token) throws android.os.RemoteException {
987            mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
988
989            if (mRestoreSets != null) {
990                for (int i = 0; i < mRestoreSets.length; i++) {
991                    if (token == mRestoreSets[i].token) {
992                        Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
993                                mRestoreTransport);
994                        msg.arg1 = token;
995                        mBackupHandler.sendMessage(msg);
996                        return 0;
997                    }
998                }
999            }
1000            return -1;
1001        }
1002
1003        public void endRestoreSession() throws android.os.RemoteException {
1004            mContext.enforceCallingPermission("android.permission.BACKUP",
1005                    "endRestoreSession");
1006
1007            mRestoreTransport.endSession();
1008            mRestoreTransport = null;
1009        }
1010    }
1011
1012
1013    @Override
1014    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1015        synchronized (mQueueLock) {
1016            int N = mBackupParticipants.size();
1017            pw.println("Participants:");
1018            for (int i=0; i<N; i++) {
1019                int uid = mBackupParticipants.keyAt(i);
1020                pw.print("  uid: ");
1021                pw.println(uid);
1022                HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1023                for (ApplicationInfo app: participants) {
1024                    pw.print("    ");
1025                    pw.println(app.toString());
1026                }
1027            }
1028            pw.println("Pending:");
1029            Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1030            while (br.hasNext()) {
1031                pw.print("    ");
1032                pw.println(br);
1033            }
1034        }
1035    }
1036}
1037