-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Profile.swift
1389 lines (1155 loc) · 56.7 KB
/
Profile.swift
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
// IMPORTANT!: Please take into consideration when adding new imports to
// this file that it is utilized by external components besides the core
// application (i.e. App Extensions). Introducing new dependencies here
// may have unintended negative consequences for App Extensions such as
// increased startup times which may lead to termination by the OS.
import Account
import Shared
import Storage
import Sync
import XCGLogger
import SyncTelemetry
import AuthenticationServices
import MozillaAppServices
// Import these dependencies ONLY for the main `Client` application target.
#if MOZ_TARGET_CLIENT
#endif
private let log = Logger.syncLogger
public let ProfileRemoteTabsSyncDelay: TimeInterval = 0.1
public protocol SyncManager {
var isSyncing: Bool { get }
var lastSyncFinishTime: Timestamp? { get set }
var syncDisplayState: SyncDisplayState? { get }
func hasSyncedHistory() -> Deferred<Maybe<Bool>>
func hasSyncedLogins() -> Deferred<Maybe<Bool>>
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
func syncBookmarks() -> SyncResult
@discardableResult func syncEverything(why: SyncReason) -> Success
func syncNamedCollections(why: SyncReason, names: [String]) -> Success
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func applicationDidEnterBackground()
func applicationDidBecomeActive()
func onNewProfile()
@discardableResult func onRemovedAccount() -> Success
@discardableResult func onAddedAccount() -> Success
}
typealias SyncFunction = (SyncDelegate, Prefs, Ready, SyncReason) -> SyncResult
class ProfileFileAccessor: FileAccessor {
convenience init(profile: Profile) {
self.init(localName: profile.localName())
}
init(localName: String) {
let profileDirName = "profile.\(localName)"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: String
let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier
if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: sharedContainerIdentifier) {
rootPath = url.path
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
}
super.init(rootPath: URL(fileURLWithPath: rootPath).appendingPathComponent(profileDirName).path)
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
public func displaySentTab(for url: URL, title: String, from deviceName: String?) {
let item = ShareItem(url: url.absoluteString, title: title, favicon: nil)
_ = self.profile.queue.addToQueue(item)
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: AnyObject {
var places: RustPlaces { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { get }
var metadata: Metadata { get }
var recommendations: HistoryRecommendations { get }
var favicons: Favicons { get }
var logins: RustLogins { get }
var certStore: CertStore { get }
var recentlyClosedTabs: ClosedTabsStore { get }
#if !MOZ_TARGET_NOTIFICATIONSERVICE
var readingList: ReadingList { get }
#endif
var isShutdown: Bool { get }
/// WARNING: Only to be called as part of the app lifecycle from the AppDelegate
/// or from App Extension code.
func _shutdown()
/// WARNING: Only to be called as part of the app lifecycle from the AppDelegate
/// or from App Extension code.
func _reopen()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// Do we have an account at all?
func hasAccount() -> Bool
// Do we have an account that (as far as we know) is in a syncable state?
func hasSyncableAccount() -> Bool
var rustFxA: RustFirefoxAccounts { get }
func removeAccount()
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getCachedClients()-> Deferred<Maybe<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func cleanupHistoryIfNeeded()
func sendQueuedSyncEvents()
@discardableResult func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func sendItem(_ item: ShareItem, toDevices devices: [RemoteDevice]) -> Success
var syncManager: SyncManager! { get }
func syncCredentialIdentities() -> Deferred<Result<Void, Error>>
func updateCredentialIdentities() -> Deferred<Result<Void, Error>>
func clearCredentialStore() -> Deferred<Result<Void, Error>>
}
extension Profile {
func syncCredentialIdentities() -> Deferred<Result<Void, Error>> {
let deferred = Deferred<Result<Void, Error>>()
self.clearCredentialStore().upon { clearResult in
self.updateCredentialIdentities().upon { updateResult in
switch (clearResult, updateResult) {
case (.success, .success):
deferred.fill(.success(()))
case (.failure(let error), _):
deferred.fill(.failure(error))
case (_, .failure(let error)):
deferred.fill(.failure(error))
}
}
}
return deferred
}
func updateCredentialIdentities() -> Deferred<Result<Void, Error>> {
let deferred = Deferred<Result<Void, Error>>()
self.logins.listLogins().upon { loginResult in
switch loginResult {
case let .failure(error):
deferred.fill(.failure(error))
case let .success(logins):
self.populateCredentialStore(
identities: logins.map(\.passwordCredentialIdentity)
).upon(deferred.fill)
}
}
return deferred
}
func populateCredentialStore(identities: [ASPasswordCredentialIdentity]) -> Deferred<Result<Void, Error>> {
let deferred = Deferred<Result<Void, Error>>()
ASCredentialIdentityStore.shared.saveCredentialIdentities(identities) { (success, error) in
if success {
deferred.fill(.success(()))
} else if let err = error {
deferred.fill(.failure(err))
}
}
return deferred
}
func clearCredentialStore() -> Deferred<Result<Void, Error>> {
let deferred = Deferred<Result<Void, Error>>()
ASCredentialIdentityStore.shared.removeAllCredentialIdentities { (success, error) in
if success {
deferred.fill(.success(()))
} else if let err = error {
deferred.fill(.failure(err))
}
}
return deferred
}
}
fileprivate let PrefKeyClientID = "PrefKeyClientID"
extension Profile {
var clientID: String {
let clientID: String
if let id = prefs.stringForKey(PrefKeyClientID) {
clientID = id
} else {
clientID = UUID().uuidString
prefs.setString(clientID, forKey: PrefKeyClientID)
}
return clientID
}
}
open class BrowserProfile: Profile {
fileprivate let name: String
fileprivate let keychain: MZKeychainWrapper
var isShutdown = false
internal let files: FileAccessor
let db: BrowserDB
let readingListDB: BrowserDB
var syncManager: SyncManager!
var syncDelegate: SyncDelegate?
/**
* N.B., BrowserProfile is used from our extensions, often via a pattern like
*
* BrowserProfile(…).foo.saveSomething(…)
*
* This can break if BrowserProfile's initializer does async work that
* subsequently — and asynchronously — expects the profile to stick around:
* see Bug 1218833. Be sure to only perform synchronous actions here.
*
* A SyncDelegate can be provided in this initializer, or once the profile is initialized.
* However, if we provide it here, it's assumed that we're initializing it from the application.
*/
init(localName: String, syncDelegate: SyncDelegate? = nil, clear: Bool = false) {
log.debug("Initing profile \(localName) on thread \(Thread.current).")
self.name = localName
self.files = ProfileFileAccessor(localName: localName)
self.keychain = MZKeychainWrapper.sharedClientAppContainerKeychain
self.syncDelegate = syncDelegate
if clear {
do {
// Remove the contents of the directory…
try self.files.removeFilesInDirectory()
// …then remove the directory itself.
try self.files.remove("")
} catch {
log.info("Cannot clear profile: \(error)")
}
}
// If the profile dir doesn't exist yet, this is first run (for this profile). The check is made here
// since the DB handles will create new DBs under the new profile folder.
let isNewProfile = !files.exists("")
// Set up our database handles.
self.db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
self.readingListDB = BrowserDB(filename: "ReadingList.db", schema: ReadingListSchema(), files: files)
if isNewProfile {
log.info("New profile. Removing old Keychain/Prefs data.")
MZKeychainWrapper.wipeKeychain()
prefs.clearAll()
}
// Log SQLite compile_options.
// db.sqliteCompileOptions() >>== { compileOptions in
// log.debug("SQLite compile_options:\n\(compileOptions.joined(separator: "\n"))")
// }
// Set up logging from Rust.
if !RustLog.shared.tryEnable({ (level, tag, message) -> Bool in
let logString = "[RUST][\(tag ?? "no-tag")] \(message)"
switch level {
case .trace:
if Logger.logPII {
log.verbose(logString)
}
case .debug:
log.debug(logString)
case .info:
log.info(logString)
case .warn:
log.warning(logString)
case .error:
SentryIntegration.shared.sendWithStacktrace(message: logString, tag: .rustLog, severity: .error)
log.error(logString)
}
return true
}) {
log.error("ERROR: Unable to enable logging from Rust")
}
// By default, filter logging from Rust below `.info` level.
try? RustLog.shared.setLevelFilter(filter: .info)
// This has to happen prior to the databases being opened, because opening them can trigger
// events to which the SyncManager listens.
self.syncManager = BrowserSyncManager(profile: self)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(onLocationChange), name: .OnLocationChange, object: nil)
notificationCenter.addObserver(self, selector: #selector(onPageMetadataFetched), name: .OnPageMetadataFetched, object: nil)
// Always start by needing invalidation.
// This is the same as self.history.setTopSitesNeedsInvalidation, but without the
// side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread.
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
if AppInfo.isChinaEdition {
// Set the default homepage.
prefs.setString(PrefsDefaults.ChineseHomePageURL, forKey: PrefsKeys.KeyDefaultHomePageURL)
if prefs.stringForKey(PrefsKeys.KeyNewTab) == nil {
prefs.setString(PrefsDefaults.ChineseHomePageURL, forKey: PrefsKeys.NewTabCustomUrlPrefKey)
prefs.setString(PrefsDefaults.ChineseNewTabDefault, forKey: PrefsKeys.KeyNewTab)
}
if prefs.stringForKey(PrefsKeys.HomePageTab) == nil {
prefs.setString(PrefsDefaults.ChineseHomePageURL, forKey: PrefsKeys.HomeButtonHomePageURL)
prefs.setString(PrefsDefaults.ChineseNewTabDefault, forKey: PrefsKeys.HomePageTab)
}
} else {
// Remove the default homepage. This does not change the user's preference,
// just the behaviour when there is no homepage.
prefs.removeObjectForKey(PrefsKeys.KeyDefaultHomePageURL)
}
// Create the "Downloads" folder in the documents directory.
if let downloadsPath = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads").path {
try? FileManager.default.createDirectory(atPath: downloadsPath, withIntermediateDirectories: true, attributes: nil)
}
}
func _reopen() {
log.debug("Reopening profile.")
isShutdown = false
if !places.isOpen && !RustFirefoxAccounts.shared.hasAccount() {
places.migrateBookmarksIfNeeded(fromBrowserDB: db)
}
db.reopenIfClosed()
_ = logins.reopenIfClosed()
_ = places.reopenIfClosed()
}
func _shutdown() {
log.debug("Shutting down profile.")
isShutdown = true
db.forceClose()
_ = logins.forceClose()
_ = places.forceClose()
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? URL, !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString {
// Only record local vists if the change notification originated from a non-private tab
if !(notification.userInfo!["isPrivate"] as? Bool ?? false) {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: Date.nowMicroseconds(), type: visitType)
history.addLocalVisit(visit)
}
history.setTopSitesNeedsInvalidation()
} else {
log.debug("Ignoring navigation.")
}
}
@objc
func onPageMetadataFetched(notification: NSNotification) {
let isPrivate = notification.userInfo?["isPrivate"] as? Bool ?? true
guard !isPrivate else {
log.debug("Private mode - Ignoring page metadata.")
return
}
guard let pageURL = notification.userInfo?["tabURL"] as? URL,
let pageMetadata = notification.userInfo?["pageMetadata"] as? PageMetadata else {
log.debug("Metadata notification doesn't contain any metadata!")
return
}
let defaultMetadataTTL: UInt64 = 3 * 24 * 60 * 60 * 1000 // 3 days for the metadata to live
self.metadata.storeMetadata(pageMetadata, forPageURL: pageURL, expireAt: defaultMetadataTTL + Date.now())
}
deinit {
log.debug("Deiniting profile \(self.localName()).")
self.syncManager.endTimedSyncs()
}
func localName() -> String {
return name
}
lazy var queue: TabQueue = {
withExtendedLifetime(self.history) {
return SQLiteQueue(db: self.db)
}
}()
/**
* Favicons, history, and tabs are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
fileprivate lazy var legacyPlaces: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations = {
return SQLiteHistory(db: self.db, prefs: self.prefs)
}()
var favicons: Favicons {
return self.legacyPlaces
}
var history: BrowserHistory & SyncableHistory & ResettableSyncStorage {
return self.legacyPlaces
}
lazy var metadata: Metadata = {
return SQLiteMetadata(db: self.db)
}()
var recommendations: HistoryRecommendations {
return self.legacyPlaces
}
lazy var placesDbPath = URL(fileURLWithPath: (try! files.getAndEnsureDirectory()), isDirectory: true).appendingPathComponent("places.db").path
lazy var places = RustPlaces(databasePath: placesDbPath)
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingList = {
return SQLiteReadingList(db: self.readingListDB)
}()
lazy var remoteClientsAndTabs: RemoteClientsAndTabs & ResettableSyncStorage & AccountRemovalDelegate & RemoteDevices = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var certStore: CertStore = {
return CertStore()
}()
lazy var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
open func getSyncDelegate() -> SyncDelegate {
return syncDelegate ?? CommandStoringSyncDelegate(profile: self)
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getCachedClients()-> Deferred<Maybe<[RemoteClient]>> {
return self.remoteClientsAndTabs.getClients()
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
public func cleanupHistoryIfNeeded() {
recommendations.cleanupHistoryIfNeeded()
}
public func sendQueuedSyncEvents() {
if !hasAccount() {
// We shouldn't be called at all if the user isn't signed in.
return
}
if syncManager.isSyncing {
// If Sync is already running, `BrowserSyncManager#endSyncing` will
// send a ping with the queued events when it's done, so don't send
// an events-only ping now.
return
}
let sendUsageData = prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true
if sendUsageData {
SyncPing.fromQueuedEvents(prefs: self.prefs,
why: .schedule) >>== { SyncTelemetry.send(ping: $0, docType: .sync) }
}
}
func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItem(_ item: ShareItem, toDevices devices: [RemoteDevice]) -> Success {
let deferred = Success()
RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in
guard let constellation = accountManager.deviceConstellation() else {
deferred.fill(Maybe(failure: NoAccountError()))
return
}
devices.forEach {
if let id = $0.id {
constellation.sendEventToDevice(targetDeviceId: id, e: .sendTab(title: item.title ?? "", url: item.url))
}
}
if let json = try? accountManager.gatherTelemetry() {
let events = FxATelemetry.parseTelemetry(fromJSONString: json)
events.forEach { $0.record(intoPrefs: self.prefs) }
}
self.sendQueuedSyncEvents()
deferred.fill(Maybe(success: ()))
}
return deferred
}
lazy var logins: RustLogins = {
let sqlCipherDatabasePath = URL(fileURLWithPath: (try! files.getAndEnsureDirectory()), isDirectory: true).appendingPathComponent("logins.db").path
let databasePath = URL(fileURLWithPath: (try! files.getAndEnsureDirectory()), isDirectory: true).appendingPathComponent("loginsPerField.db").path
return RustLogins(sqlCipherDatabasePath: sqlCipherDatabasePath, databasePath: databasePath)
}()
func hasAccount() -> Bool {
return rustFxA.hasAccount()
}
func hasSyncableAccount() -> Bool {
return hasAccount() && !rustFxA.accountNeedsReauth()
}
var rustFxA: RustFirefoxAccounts {
return RustFirefoxAccounts.shared
}
func removeAccount() {
RustFirefoxAccounts.shared.disconnect()
// Not available in extensions
#if !MOZ_TARGET_NOTIFICATIONSERVICE && !MOZ_TARGET_SHARETO && !MOZ_TARGET_CREDENTIAL_PROVIDER
unregisterRemoteNotifiation()
#endif
// remove Account Metadata
prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
// Save the keys that will be restored
let rustLoginsKeys = RustLoginEncryptionKeys()
let perFieldKey = keychain.string(forKey: rustLoginsKeys.loginPerFieldKeychainKey)
let sqlCipherKey = keychain.string(forKey: rustLoginsKeys.loginsUnlockKeychainKey)
let sqlCipherSalt = keychain.string(forKey: rustLoginsKeys.loginPerFieldKeychainKey)
// Remove all items, removal is not key-by-key specific (due to the risk of failing to delete something), simply restore what is needed.
keychain.removeAllKeys()
// Restore the keys that are still needed
if let sqlCipherKey = sqlCipherKey {
keychain.set(sqlCipherKey, forKey: rustLoginsKeys.loginsUnlockKeychainKey, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock)
}
if let sqlCipherSalt = sqlCipherSalt {
keychain.set(sqlCipherSalt, forKey: rustLoginsKeys.loginsSaltKeychainKey, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock)
}
if let perFieldKey = perFieldKey {
keychain.set(perFieldKey, forKey: rustLoginsKeys.loginPerFieldKeychainKey, withAccessibility: .afterFirstUnlock)
}
// Tell any observers that our account has changed.
NotificationCenter.default.post(name: .FirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount()
}
// Profile exists in extensions, UIApp is unavailable there, make this code run for the main app only
@available(iOSApplicationExtension, unavailable, message: "UIApplication.shared is unavailable in application extensions")
private func unregisterRemoteNotifiation() {
if let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as? UIApplication {
application.unregisterForRemoteNotifications()
}
}
class NoAccountError: MaybeErrorType {
var description = "No account."
}
// Extends NSObject so we can use timers.
public class BrowserSyncManager: NSObject, SyncManager, CollectionChangedNotifier {
// We shouldn't live beyond our containing BrowserProfile, either in the main app or in
// an extension.
// But it's possible that we'll finish a side-effect sync after we've ditched the profile
// as a whole, so we hold on to our Prefs, potentially for a little while longer. This is
// safe as a strong reference, because there's no cycle.
unowned fileprivate let profile: BrowserProfile
fileprivate let prefs: Prefs
fileprivate var constellationStateUpdate: Any?
let FifteenMinutes = TimeInterval(60 * 15)
let OneMinute = TimeInterval(60)
fileprivate var syncTimer: Timer?
fileprivate var backgrounded: Bool = true
public func applicationDidEnterBackground() {
self.backgrounded = true
self.endTimedSyncs()
}
deinit {
if let c = constellationStateUpdate {
NotificationCenter.default.removeObserver(c)
}
}
public func applicationDidBecomeActive() {
self.backgrounded = false
guard self.profile.hasSyncableAccount() else {
return
}
self.beginTimedSyncs()
// Sync now if it's been more than our threshold.
let now = Date.now()
let then = self.lastSyncFinishTime ?? 0
guard now >= then else {
log.debug("Time was modified since last sync.")
self.syncEverythingSoon()
return
}
let since = now - then
log.debug("\(since)msec since last sync.")
if since > SyncConstants.SyncOnForegroundMinimumDelayMillis {
self.syncEverythingSoon()
}
}
/**
* Locking is managed by syncSeveral. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
fileprivate let syncLock = NSRecursiveLock()
public var isSyncing: Bool {
syncLock.lock()
defer { syncLock.unlock() }
return syncDisplayState != nil && syncDisplayState! == .inProgress
}
public var syncDisplayState: SyncDisplayState?
// The dispatch queue for coordinating syncing and resetting the database.
fileprivate let syncQueue = DispatchQueue(label: "com.mozilla.firefox.sync")
fileprivate typealias EngineResults = [(EngineIdentifier, SyncStatus)]
fileprivate typealias EngineTasks = [(EngineIdentifier, SyncFunction)]
// Used as a task queue for syncing.
fileprivate var syncReducer: AsyncReducer<EngineResults, EngineTasks>?
fileprivate func beginSyncing() {
notifySyncing(notification: .ProfileDidStartSyncing)
}
fileprivate func endSyncing(_ result: SyncOperationResult) {
// loop through statuses and fill sync state
syncLock.lock()
defer { syncLock.unlock() }
log.info("Ending all queued syncs.")
syncDisplayState = SyncStatusResolver(engineResults: result.engineResults).resolveResults()
#if MOZ_TARGET_CLIENT
if canSendUsageData() {
SyncPing.from(result: result,
remoteClientsAndTabs: profile.remoteClientsAndTabs,
prefs: prefs,
why: .schedule) >>== { SyncTelemetry.send(ping: $0, docType: .sync) }
} else {
log.debug("Profile isn't sending usage data. Not sending sync status event.")
}
#endif
// Dont notify if we are performing a sync in the background. This prevents more db access from happening
if !self.backgrounded {
notifySyncing(notification: .ProfileDidFinishSyncing)
}
syncReducer = nil
}
func canSendUsageData() -> Bool {
return profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true
}
private func notifySyncing(notification: Notification.Name) {
NotificationCenter.default.post(name: notification, object: syncDisplayState?.asObject())
}
init(profile: BrowserProfile) {
self.profile = profile
self.prefs = profile.prefs
super.init()
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(onDatabaseWasRecreated), name: .DatabaseWasRecreated, object: nil)
center.addObserver(self, selector: #selector(onLoginDidChange), name: .DataLoginDidChange, object: nil)
center.addObserver(self, selector: #selector(onStartSyncing), name: .ProfileDidStartSyncing, object: nil)
center.addObserver(self, selector: #selector(onFinishSyncing), name: .ProfileDidFinishSyncing, object: nil)
}
// TODO: Do we still need this/do we need to do this for our new DB too?
private func handleRecreationOfDatabaseNamed(name: String?) -> Success {
let browserCollections = ["history", "tabs"]
let dbName = name ?? "<all>"
switch dbName {
case "<all>", "browser.db":
return self.locallyResetCollections(browserCollections)
default:
log.debug("Unknown database \(dbName).")
return succeed()
}
}
func doInBackgroundAfter(_ millis: Int64, _ block: @escaping () -> Void) {
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
//Pretty ambiguous here. I'm thinking .now was DispatchTime.now() and not Date.now()
queue.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(millis)), execute: block)
}
@objc
func onDatabaseWasRecreated(notification: NSNotification) {
log.debug("Database was recreated.")
let name = notification.object as? String
log.debug("Database was \(name ?? "nil").")
// We run this in the background after a few hundred milliseconds;
// it doesn't really matter when it runs, so long as it doesn't
// happen in the middle of a sync.
let resetDatabase = {
return self.handleRecreationOfDatabaseNamed(name: name) >>== {
log.debug("Reset of \(name ?? "nil") done")
}
}
self.doInBackgroundAfter(300) {
self.syncLock.lock()
defer { self.syncLock.unlock() }
// If we're syncing already, then wait for sync to end,
// then reset the database on the same serial queue.
if let reducer = self.syncReducer, !reducer.isFilled {
reducer.terminal.upon { _ in
self.syncQueue.async(execute: resetDatabase)
}
} else {
// Otherwise, reset the database on the sync queue now
// Sync can't start while this is still going on.
self.syncQueue.async(execute: resetDatabase)
}
}
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(_ notification: NSNotification) {
log.debug("Login did change.")
if (Date.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = Date.now()
// Give it a few seconds.
// Trigger on the main queue. The bulk of the sync work runs in the background.
let greenLight = self.greenLight()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(SyncConstants.SyncDelayTriggered)) {
if greenLight() {
self.syncLogins()
}
}
}
}
public var lastSyncFinishTime: Timestamp? {
get {
return self.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime)
}
set(value) {
if let value = value {
self.prefs.setTimestamp(value, forKey: PrefsKeys.KeyLastSyncFinishTime)
} else {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastSyncFinishTime)
}
}
}
@objc func onStartSyncing(_ notification: NSNotification) {
syncLock.lock()
defer { syncLock.unlock() }
syncDisplayState = .inProgress
}
@objc func onFinishSyncing(_ notification: NSNotification) {
syncLock.lock()
defer { syncLock.unlock() }
if let syncState = syncDisplayState, syncState == .good {
self.lastSyncFinishTime = Date.now()
}
}
var prefsForSync: Prefs {
return self.prefs.branch("sync")
}
public func onAddedAccount() -> Success {
// Only sync if we're green lit. This makes sure that we don't sync unverified accounts.
guard self.profile.hasSyncableAccount() else { return succeed() }
self.beginTimedSyncs()
return self.syncEverything(why: .didLogin)
}
func locallyResetCollections(_ collections: [String]) -> Success {
return walk(collections, f: self.locallyResetCollection)
}
func locallyResetCollection(_ collection: String) -> Success {
switch collection {
case "bookmarks":
return self.profile.places.resetBookmarksMetadata()
case "clients":
fallthrough
case "tabs":
// Because clients and tabs share storage, and thus we wipe data for both if we reset either,
// we reset the prefs for both at the same time.
return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync)
case "history":
return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history")
case "passwords":
return self.profile.logins.resetSync()
case "forms":
log.debug("Requested reset for forms, but this client doesn't sync them yet.")
return succeed()
case "addons":
log.debug("Requested reset for addons, but this client doesn't sync them.")
return succeed()
case "prefs":
log.debug("Requested reset for prefs, but this client doesn't sync them.")
return succeed()
default:
log.warning("Asked to reset collection \(collection), which we don't know about.")
return succeed()
}
}
public func onNewProfile() {
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
public func onRemovedAccount() -> Success {
let profile = self.profile
// Run these in order, because they might write to the same DB!
let remove = [
profile.history.onRemovedAccount,
profile.remoteClientsAndTabs.onRemovedAccount,
profile.logins.resetSync,
profile.places.resetBookmarksMetadata,
]
let clearPrefs: () -> Success = {
withExtendedLifetime(self) {
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
return succeed()
}
return accumulate(remove) >>> clearPrefs
}
fileprivate func repeatingTimerAtInterval(_ interval: TimeInterval, selector: Selector) -> Timer {
return Timer.scheduledTimer(timeInterval: interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
public func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = #selector(syncOnTimer)
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
public func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
fileprivate func syncClientsWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult {
log.debug("Syncing clients to storage.")
if constellationStateUpdate == nil {
constellationStateUpdate = NotificationCenter.default.addObserver(forName: .constellationStateUpdate, object: nil, queue: .main) { [weak self] notification in
guard let accountManager = self?.profile.rustFxA.accountManager.peek(), let state = accountManager.deviceConstellation()?.state() else {
return
}
guard let self = self else { return }
let devices = state.remoteDevices.map { d -> RemoteDevice in
let t = "\(d.deviceType)"
let lastAccessTime = d.lastAccessTime == nil ? nil : UInt64(clamping: d.lastAccessTime!)
return RemoteDevice(id: d.id, name: d.displayName, type: t, isCurrentDevice: d.isCurrentDevice, lastAccessTime: lastAccessTime, availableCommands: nil)
}
let _ = self.profile.remoteClientsAndTabs.replaceRemoteDevices(devices)
}
}
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs, why: why)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info, notifier: self) >>== { result in
guard case .completed = result, let accountManager = self.profile.rustFxA.accountManager.peek() else {
return deferMaybe(result)
}
log.debug("Updating FxA devices list.")
accountManager.deviceConstellation()?.refreshState()
return deferMaybe(result)
}
}
fileprivate func syncTabsWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs, why: why)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)