-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBackupManagerService.java
More file actions
5772 lines (5133 loc) · 254 KB
/
Copy pathBackupManagerService.java
File metadata and controls
5772 lines (5133 loc) · 254 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import android.app.ActivityManagerNative;
import android.app.AlarmManager;
import android.app.AppGlobals;
import android.app.IActivityManager;
import android.app.IApplicationThread;
import android.app.IBackupAgent;
import android.app.PendingIntent;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataOutput;
import android.app.backup.FullBackup;
import android.app.backup.RestoreSet;
import android.app.backup.IBackupManager;
import android.app.backup.IFullBackupRestoreObserver;
import android.app.backup.IRestoreObserver;
import android.app.backup.IRestoreSession;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.IPackageManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.WorkSource;
import android.os.storage.IMountService;
import android.provider.Settings;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;
import android.util.SparseArray;
import android.util.StringBuilderPrinter;
import com.android.internal.backup.BackupConstants;
import com.android.internal.backup.IBackupTransport;
import com.android.internal.backup.LocalTransport;
import com.android.server.PackageManagerBackupAgent.Metadata;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
class BackupManagerService extends IBackupManager.Stub {
private static final String TAG = "BackupManagerService";
private static final boolean DEBUG = true;
private static final boolean MORE_DEBUG = false;
// Name and current contents version of the full-backup manifest file
static final String BACKUP_MANIFEST_FILENAME = "_manifest";
static final int BACKUP_MANIFEST_VERSION = 1;
static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
static final int BACKUP_FILE_VERSION = 1;
static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
// How often we perform a backup pass. Privileged external callers can
// trigger an immediate pass.
private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
// Random variation in backup scheduling time to avoid server load spikes
private static final int FUZZ_MILLIS = 5 * 60 * 1000;
// The amount of time between the initial provisioning of the device and
// the first backup pass.
private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
private static final int MSG_RUN_BACKUP = 1;
private static final int MSG_RUN_FULL_BACKUP = 2;
private static final int MSG_RUN_RESTORE = 3;
private static final int MSG_RUN_CLEAR = 4;
private static final int MSG_RUN_INITIALIZE = 5;
private static final int MSG_RUN_GET_RESTORE_SETS = 6;
private static final int MSG_TIMEOUT = 7;
private static final int MSG_RESTORE_TIMEOUT = 8;
private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
private static final int MSG_RUN_FULL_RESTORE = 10;
// backup task state machine tick
static final int MSG_BACKUP_RESTORE_STEP = 20;
static final int MSG_OP_COMPLETE = 21;
// Timeout interval for deciding that a bind or clear-data has taken too long
static final long TIMEOUT_INTERVAL = 10 * 1000;
// Timeout intervals for agent backup & restore operations
static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
// User confirmation timeout for a full backup/restore operation. It's this long in
// order to give them time to enter the backup password.
static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
private Context mContext;
private PackageManager mPackageManager;
IPackageManager mPackageManagerBinder;
private IActivityManager mActivityManager;
private PowerManager mPowerManager;
private AlarmManager mAlarmManager;
private IMountService mMountService;
IBackupManager mBackupManagerBinder;
boolean mEnabled; // access to this is synchronized on 'this'
boolean mProvisioned;
boolean mAutoRestore;
PowerManager.WakeLock mWakelock;
HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
BackupHandler mBackupHandler;
PendingIntent mRunBackupIntent, mRunInitIntent;
BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
// map UIDs to the set of backup client services within that UID's app set
final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
= new SparseArray<HashSet<ApplicationInfo>>();
// set of backup services that have pending changes
class BackupRequest {
public String packageName;
BackupRequest(String pkgName) {
packageName = pkgName;
}
public String toString() {
return "BackupRequest{pkg=" + packageName + "}";
}
}
// Backups that we haven't started yet. Keys are package names.
HashMap<String,BackupRequest> mPendingBackups
= new HashMap<String,BackupRequest>();
// Pseudoname that we use for the Package Manager metadata "package"
static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
// locking around the pending-backup management
final Object mQueueLock = new Object();
// The thread performing the sequence of queued backups binds to each app's agent
// in succession. Bind notifications are asynchronously delivered through the
// Activity Manager; use this lock object to signal when a requested binding has
// completed.
final Object mAgentConnectLock = new Object();
IBackupAgent mConnectedAgent;
volatile boolean mBackupRunning;
volatile boolean mConnecting;
volatile long mLastBackupPass;
volatile long mNextBackupPass;
// A similar synchronization mechanism around clearing apps' data for restore
final Object mClearDataLock = new Object();
volatile boolean mClearingData;
// Transport bookkeeping
final HashMap<String,IBackupTransport> mTransports
= new HashMap<String,IBackupTransport>();
String mCurrentTransport;
IBackupTransport mLocalTransport, mGoogleTransport;
ActiveRestoreSession mActiveRestoreSession;
class RestoreGetSetsParams {
public IBackupTransport transport;
public ActiveRestoreSession session;
public IRestoreObserver observer;
RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
IRestoreObserver _observer) {
transport = _transport;
session = _session;
observer = _observer;
}
}
class RestoreParams {
public IBackupTransport transport;
public IRestoreObserver observer;
public long token;
public PackageInfo pkgInfo;
public int pmToken; // in post-install restore, the PM's token for this transaction
public boolean needFullBackup;
public String[] filterSet;
RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
transport = _transport;
observer = _obs;
token = _token;
pkgInfo = _pkg;
pmToken = _pmToken;
needFullBackup = _needFullBackup;
filterSet = null;
}
RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
boolean _needFullBackup) {
transport = _transport;
observer = _obs;
token = _token;
pkgInfo = null;
pmToken = 0;
needFullBackup = _needFullBackup;
filterSet = null;
}
RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
String[] _filterSet, boolean _needFullBackup) {
transport = _transport;
observer = _obs;
token = _token;
pkgInfo = null;
pmToken = 0;
needFullBackup = _needFullBackup;
filterSet = _filterSet;
}
}
class ClearParams {
public IBackupTransport transport;
public PackageInfo packageInfo;
ClearParams(IBackupTransport _transport, PackageInfo _info) {
transport = _transport;
packageInfo = _info;
}
}
class FullParams {
public ParcelFileDescriptor fd;
public final AtomicBoolean latch;
public IFullBackupRestoreObserver observer;
public String curPassword; // filled in by the confirmation step
public String encryptPassword;
FullParams() {
latch = new AtomicBoolean(false);
}
}
class FullBackupParams extends FullParams {
public boolean includeApks;
public boolean includeShared;
public boolean allApps;
public boolean includeSystem;
public String[] packages;
FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
boolean doAllApps, boolean doSystem, String[] pkgList) {
fd = output;
includeApks = saveApks;
includeShared = saveShared;
allApps = doAllApps;
includeSystem = doSystem;
packages = pkgList;
}
}
class FullRestoreParams extends FullParams {
FullRestoreParams(ParcelFileDescriptor input) {
fd = input;
}
}
// Bookkeeping of in-flight operations for timeout etc. purposes. The operation
// token is the index of the entry in the pending-operations list.
static final int OP_PENDING = 0;
static final int OP_ACKNOWLEDGED = 1;
static final int OP_TIMEOUT = -1;
class Operation {
public int state;
public BackupRestoreTask callback;
Operation(int initialState, BackupRestoreTask callbackObj) {
state = initialState;
callback = callbackObj;
}
}
final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
final Object mCurrentOpLock = new Object();
final Random mTokenGenerator = new Random();
final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
// Where we keep our journal files and other bookkeeping
File mBaseStateDir;
File mDataDir;
File mJournalDir;
File mJournal;
// Backup password, if any, and the file where it's saved. What is stored is not the
// password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
// persisted) salt. Validation is performed by running the challenge text through the
// same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
// the saved hash string, then the challenge text matches the originally supplied
// password text.
private final SecureRandom mRng = new SecureRandom();
private String mPasswordHash;
private File mPasswordHashFile;
private byte[] mPasswordSalt;
// Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
static final int PBKDF2_HASH_ROUNDS = 10000;
static final int PBKDF2_KEY_SIZE = 256; // bits
static final int PBKDF2_SALT_SIZE = 512; // bits
static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
// Keep a log of all the apps we've ever backed up, and what the
// dataset tokens are for both the current backup dataset and
// the ancestral dataset.
private File mEverStored;
HashSet<String> mEverStoredApps = new HashSet<String>();
static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
File mTokenFile;
Set<String> mAncestralPackages = null;
long mAncestralToken = 0;
long mCurrentToken = 0;
// Persistently track the need to do a full init
static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
HashSet<String> mPendingInits = new HashSet<String>(); // transport names
// Utility: build a new random integer token
int generateToken() {
int token;
do {
synchronized (mTokenGenerator) {
token = mTokenGenerator.nextInt();
}
} while (token < 0);
return token;
}
// ----- Asynchronous backup/restore handler thread -----
private class BackupHandler extends Handler {
public BackupHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_RUN_BACKUP:
{
mLastBackupPass = System.currentTimeMillis();
mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
IBackupTransport transport = getTransport(mCurrentTransport);
if (transport == null) {
Slog.v(TAG, "Backup requested but no transport available");
synchronized (mQueueLock) {
mBackupRunning = false;
}
mWakelock.release();
break;
}
// snapshot the pending-backup set and work on that
ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
File oldJournal = mJournal;
synchronized (mQueueLock) {
// Do we have any work to do? Construct the work queue
// then release the synchronization lock to actually run
// the backup.
if (mPendingBackups.size() > 0) {
for (BackupRequest b: mPendingBackups.values()) {
queue.add(b);
}
if (DEBUG) Slog.v(TAG, "clearing pending backups");
mPendingBackups.clear();
// Start a new backup-queue journal file too
mJournal = null;
}
}
// At this point, we have started a new journal file, and the old
// file identity is being passed to the backup processing task.
// When it completes successfully, that old journal file will be
// deleted. If we crash prior to that, the old journal is parsed
// at next boot and the journaled requests fulfilled.
if (queue.size() > 0) {
// Spin up a backup state sequence and set it running
PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
sendMessage(pbtMessage);
} else {
Slog.v(TAG, "Backup requested but nothing pending");
synchronized (mQueueLock) {
mBackupRunning = false;
}
mWakelock.release();
}
break;
}
case MSG_BACKUP_RESTORE_STEP:
{
try {
BackupRestoreTask task = (BackupRestoreTask) msg.obj;
if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
task.execute();
} catch (ClassCastException e) {
Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
}
break;
}
case MSG_OP_COMPLETE:
{
try {
BackupRestoreTask task = (BackupRestoreTask) msg.obj;
task.operationComplete();
} catch (ClassCastException e) {
Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
}
break;
}
case MSG_RUN_FULL_BACKUP:
{
// TODO: refactor full backup to be a looper-based state machine
// similar to normal backup/restore.
FullBackupParams params = (FullBackupParams)msg.obj;
PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
params.observer, params.includeApks,
params.includeShared, params.curPassword, params.encryptPassword,
params.allApps, params.includeSystem, params.packages, params.latch);
(new Thread(task)).start();
break;
}
case MSG_RUN_RESTORE:
{
RestoreParams params = (RestoreParams)msg.obj;
Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
PerformRestoreTask task = new PerformRestoreTask(
params.transport, params.observer,
params.token, params.pkgInfo, params.pmToken,
params.needFullBackup, params.filterSet);
Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
sendMessage(restoreMsg);
break;
}
case MSG_RUN_FULL_RESTORE:
{
// TODO: refactor full restore to be a looper-based state machine
// similar to normal backup/restore.
FullRestoreParams params = (FullRestoreParams)msg.obj;
PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
params.curPassword, params.encryptPassword,
params.observer, params.latch);
(new Thread(task)).start();
break;
}
case MSG_RUN_CLEAR:
{
ClearParams params = (ClearParams)msg.obj;
(new PerformClearTask(params.transport, params.packageInfo)).run();
break;
}
case MSG_RUN_INITIALIZE:
{
HashSet<String> queue;
// Snapshot the pending-init queue and work on that
synchronized (mQueueLock) {
queue = new HashSet<String>(mPendingInits);
mPendingInits.clear();
}
(new PerformInitializeTask(queue)).run();
break;
}
case MSG_RUN_GET_RESTORE_SETS:
{
// Like other async operations, this is entered with the wakelock held
RestoreSet[] sets = null;
RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
try {
sets = params.transport.getAvailableRestoreSets();
// cache the result in the active session
synchronized (params.session) {
params.session.mRestoreSets = sets;
}
if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
} catch (Exception e) {
Slog.e(TAG, "Error from transport getting set list");
} finally {
if (params.observer != null) {
try {
params.observer.restoreSetsAvailable(sets);
} catch (RemoteException re) {
Slog.e(TAG, "Unable to report listing to observer");
} catch (Exception e) {
Slog.e(TAG, "Restore observer threw", e);
}
}
// Done: reset the session timeout clock
removeMessages(MSG_RESTORE_TIMEOUT);
sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
mWakelock.release();
}
break;
}
case MSG_TIMEOUT:
{
handleTimeout(msg.arg1, msg.obj);
break;
}
case MSG_RESTORE_TIMEOUT:
{
synchronized (BackupManagerService.this) {
if (mActiveRestoreSession != null) {
// Client app left the restore session dangling. We know that it
// can't be in the middle of an actual restore operation because
// the timeout is suspended while a restore is in progress. Clean
// up now.
Slog.w(TAG, "Restore session timed out; aborting");
post(mActiveRestoreSession.new EndRestoreRunnable(
BackupManagerService.this, mActiveRestoreSession));
}
}
}
case MSG_FULL_CONFIRMATION_TIMEOUT:
{
synchronized (mFullConfirmations) {
FullParams params = mFullConfirmations.get(msg.arg1);
if (params != null) {
Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
// Release the waiter; timeout == completion
signalFullBackupRestoreCompletion(params);
// Remove the token from the set
mFullConfirmations.delete(msg.arg1);
// Report a timeout to the observer, if any
if (params.observer != null) {
try {
params.observer.onTimeout();
} catch (RemoteException e) {
/* don't care if the app has gone away */
}
}
} else {
Slog.d(TAG, "couldn't find params for token " + msg.arg1);
}
}
break;
}
}
}
}
// ----- Main service implementation -----
public BackupManagerService(Context context) {
mContext = context;
mPackageManager = context.getPackageManager();
mPackageManagerBinder = AppGlobals.getPackageManager();
mActivityManager = ActivityManagerNative.getDefault();
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
mBackupManagerBinder = asInterface(asBinder());
// spin up the backup/restore handler thread
mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
// Set up our bookkeeping
boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.BACKUP_ENABLED, 0) != 0;
mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
// If Encrypted file systems is enabled or disabled, this call will return the
// correct directory.
mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
mBaseStateDir.mkdirs();
mDataDir = Environment.getDownloadCacheDirectory();
mPasswordHashFile = new File(mBaseStateDir, "pwhash");
if (mPasswordHashFile.exists()) {
FileInputStream fin = null;
DataInputStream in = null;
try {
fin = new FileInputStream(mPasswordHashFile);
in = new DataInputStream(new BufferedInputStream(fin));
// integer length of the salt array, followed by the salt,
// then the hex pw hash string
int saltLen = in.readInt();
byte[] salt = new byte[saltLen];
in.readFully(salt);
mPasswordHash = in.readUTF();
mPasswordSalt = salt;
} catch (IOException e) {
Slog.e(TAG, "Unable to read saved backup pw hash");
} finally {
try {
if (in != null) in.close();
if (fin != null) fin.close();
} catch (IOException e) {
Slog.w(TAG, "Unable to close streams");
}
}
}
// Alarm receivers for scheduled backups & initialization operations
mRunBackupReceiver = new RunBackupReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(RUN_BACKUP_ACTION);
context.registerReceiver(mRunBackupReceiver, filter,
android.Manifest.permission.BACKUP, null);
mRunInitReceiver = new RunInitializeReceiver();
filter = new IntentFilter();
filter.addAction(RUN_INITIALIZE_ACTION);
context.registerReceiver(mRunInitReceiver, filter,
android.Manifest.permission.BACKUP, null);
Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
// Set up the backup-request journaling
mJournalDir = new File(mBaseStateDir, "pending");
mJournalDir.mkdirs(); // creates mBaseStateDir along the way
mJournal = null; // will be created on first use
// Set up the various sorts of package tracking we do
initPackageTracking();
// Build our mapping of uid to backup client services. This implicitly
// schedules a backup pass on the Package Manager metadata the first
// time anything needs to be backed up.
synchronized (mBackupParticipants) {
addPackageParticipantsLocked(null);
}
// Set up our transport options and initialize the default transport
// TODO: Have transports register themselves somehow?
// TODO: Don't create transports that we don't need to?
mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
ComponentName localName = new ComponentName(context, LocalTransport.class);
registerTransport(localName.flattenToShortString(), mLocalTransport);
mGoogleTransport = null;
mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.BACKUP_TRANSPORT);
if ("".equals(mCurrentTransport)) {
mCurrentTransport = null;
}
if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
// Attach to the Google backup transport. When this comes up, it will set
// itself as the current transport because we explicitly reset mCurrentTransport
// to null.
ComponentName transportComponent = new ComponentName("com.google.android.backup",
"com.google.android.backup.BackupTransportService");
try {
// If there's something out there that is supposed to be the Google
// backup transport, make sure it's legitimately part of the OS build
// and not an app lying about its package name.
ApplicationInfo info = mPackageManager.getApplicationInfo(
transportComponent.getPackageName(), 0);
if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
if (DEBUG) Slog.v(TAG, "Binding to Google transport");
Intent intent = new Intent().setComponent(transportComponent);
context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
} else {
Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
}
} catch (PackageManager.NameNotFoundException nnf) {
// No such package? No binding.
if (DEBUG) Slog.v(TAG, "Google transport not present");
}
// Now that we know about valid backup participants, parse any
// leftover journal files into the pending backup set
parseLeftoverJournals();
// Power management
mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
// Start the backup passes going
setBackupEnabled(areEnabled);
}
private class RunBackupReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
synchronized (mQueueLock) {
if (mPendingInits.size() > 0) {
// If there are pending init operations, we process those
// and then settle into the usual periodic backup schedule.
if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
try {
mAlarmManager.cancel(mRunInitIntent);
mRunInitIntent.send();
} catch (PendingIntent.CanceledException ce) {
Slog.e(TAG, "Run init intent cancelled");
// can't really do more than bail here
}
} else {
// Don't run backups now if we're disabled or not yet
// fully set up.
if (mEnabled && mProvisioned) {
if (!mBackupRunning) {
if (DEBUG) Slog.v(TAG, "Running a backup pass");
// Acquire the wakelock and pass it to the backup thread. it will
// be released once backup concludes.
mBackupRunning = true;
mWakelock.acquire();
Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
mBackupHandler.sendMessage(msg);
} else {
Slog.i(TAG, "Backup time but one already running");
}
} else {
Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
}
}
}
}
}
}
private class RunInitializeReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
synchronized (mQueueLock) {
if (DEBUG) Slog.v(TAG, "Running a device init");
// Acquire the wakelock and pass it to the init thread. it will
// be released once init concludes.
mWakelock.acquire();
Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
mBackupHandler.sendMessage(msg);
}
}
}
}
private void initPackageTracking() {
if (DEBUG) Slog.v(TAG, "Initializing package tracking");
// Remember our ancestral dataset
mTokenFile = new File(mBaseStateDir, "ancestral");
try {
RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
int version = tf.readInt();
if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
mAncestralToken = tf.readLong();
mCurrentToken = tf.readLong();
int numPackages = tf.readInt();
if (numPackages >= 0) {
mAncestralPackages = new HashSet<String>();
for (int i = 0; i < numPackages; i++) {
String pkgName = tf.readUTF();
mAncestralPackages.add(pkgName);
}
}
}
tf.close();
} catch (FileNotFoundException fnf) {
// Probably innocuous
Slog.v(TAG, "No ancestral data");
} catch (IOException e) {
Slog.w(TAG, "Unable to read token file", e);
}
// Keep a log of what apps we've ever backed up. Because we might have
// rebooted in the middle of an operation that was removing something from
// this log, we sanity-check its contents here and reconstruct it.
mEverStored = new File(mBaseStateDir, "processed");
File tempProcessedFile = new File(mBaseStateDir, "processed.new");
// If we were in the middle of removing something from the ever-backed-up
// file, there might be a transient "processed.new" file still present.
// Ignore it -- we'll validate "processed" against the current package set.
if (tempProcessedFile.exists()) {
tempProcessedFile.delete();
}
// If there are previous contents, parse them out then start a new
// file to continue the recordkeeping.
if (mEverStored.exists()) {
RandomAccessFile temp = null;
RandomAccessFile in = null;
try {
temp = new RandomAccessFile(tempProcessedFile, "rws");
in = new RandomAccessFile(mEverStored, "r");
while (true) {
PackageInfo info;
String pkg = in.readUTF();
try {
info = mPackageManager.getPackageInfo(pkg, 0);
mEverStoredApps.add(pkg);
temp.writeUTF(pkg);
if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
} catch (NameNotFoundException e) {
// nope, this package was uninstalled; don't include it
if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
}
}
} catch (EOFException e) {
// Once we've rewritten the backup history log, atomically replace the
// old one with the new one then reopen the file for continuing use.
if (!tempProcessedFile.renameTo(mEverStored)) {
Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
}
} catch (IOException e) {
Slog.e(TAG, "Error in processed file", e);
} finally {
try { if (temp != null) temp.close(); } catch (IOException e) {}
try { if (in != null) in.close(); } catch (IOException e) {}
}
}
// Register for broadcasts about package install, etc., so we can
// update the provider list.
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addDataScheme("package");
mContext.registerReceiver(mBroadcastReceiver, filter);
// Register for events related to sdcard installation.
IntentFilter sdFilter = new IntentFilter();
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
mContext.registerReceiver(mBroadcastReceiver, sdFilter);
}
private void parseLeftoverJournals() {
for (File f : mJournalDir.listFiles()) {
if (mJournal == null || f.compareTo(mJournal) != 0) {
// This isn't the current journal, so it must be a leftover. Read
// out the package names mentioned there and schedule them for
// backup.
RandomAccessFile in = null;
try {
Slog.i(TAG, "Found stale backup journal, scheduling");
in = new RandomAccessFile(f, "r");
while (true) {
String packageName = in.readUTF();
Slog.i(TAG, " " + packageName);
dataChangedImpl(packageName);
}
} catch (EOFException e) {
// no more data; we're done
} catch (Exception e) {
Slog.e(TAG, "Can't read " + f, e);
} finally {
// close/delete the file
try { if (in != null) in.close(); } catch (IOException e) {}
f.delete();
}
}
}
}
private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
return buildCharArrayKey(pw.toCharArray(), salt, rounds);
}
private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
return keyFactory.generateSecret(ks);
} catch (InvalidKeySpecException e) {
Slog.e(TAG, "Invalid key spec for PBKDF2!");
} catch (NoSuchAlgorithmException e) {
Slog.e(TAG, "PBKDF2 unavailable!");
}
return null;
}
private String buildPasswordHash(String pw, byte[] salt, int rounds) {
SecretKey key = buildPasswordKey(pw, salt, rounds);
if (key != null) {
return byteArrayToHex(key.getEncoded());
}
return null;