-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathMessageSender.swift
1917 lines (1699 loc) · 82.5 KB
/
MessageSender.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
//
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import Foundation
import LibSignalClient
// MARK: - Message "isXYZ" properties
private extension TSOutgoingMessage {
var isTransientSKDM: Bool {
(self as? OWSOutgoingSenderKeyDistributionMessage)?.isSentOnBehalfOfOnlineMessage ?? false
}
var isResendRequest: Bool {
self is OWSOutgoingResendRequest
}
var isSyncMessage: Bool { self is OWSOutgoingSyncMessage }
var canSendToLocalAddress: Bool {
return (isSyncMessage ||
self is OWSOutgoingCallMessage ||
self is OWSOutgoingResendRequest ||
self is OWSOutgoingResendResponse)
}
}
// MARK: - MessageSender
public class MessageSender {
private var preKeyManager: PreKeyManager { DependenciesBridge.shared.preKeyManager }
private let groupSendEndorsementStore: any GroupSendEndorsementStore
init(groupSendEndorsementStore: any GroupSendEndorsementStore) {
self.groupSendEndorsementStore = groupSendEndorsementStore
SwiftSingletons.register(self)
}
private let pendingTasks = PendingTasks(label: "Message Sends")
public func pendingSendsPromise() -> Promise<Void> {
// This promise blocks on all operations already in the queue,
// but will not block on new operations added after this promise
// is created. That's intentional to ensure that NotificationService
// instances complete in a timely way.
pendingTasks.pendingTasksPromise()
}
// MARK: - Creating Signal Protocol Sessions
private func containsValidSession(for serviceId: ServiceId, deviceId: UInt32, tx: DBReadTransaction) throws -> Bool {
let sessionStore = DependenciesBridge.shared.signalProtocolStoreManager.signalProtocolStore(for: .aci).sessionStore
do {
guard let session = try sessionStore.loadSession(for: serviceId, deviceId: deviceId, tx: tx) else {
return false
}
return session.hasCurrentState
} catch {
switch error {
case RecipientIdError.mustNotUsePniBecauseAciExists:
throw error
default:
return false
}
}
}
/// Establishes a session with the recipient if one doesn't already exist.
private func ensureRecipientHasSession(
recipientUniqueId: RecipientUniqueId,
serviceId: ServiceId,
deviceId: UInt32,
isOnlineMessage: Bool,
isTransientSenderKeyDistributionMessage: Bool,
sealedSenderParameters: SealedSenderParameters?
) async throws {
let hasSession = try SSKEnvironment.shared.databaseStorageRef.read { tx in
try containsValidSession(for: serviceId, deviceId: deviceId, tx: tx.asV2Read)
}
if hasSession {
return
}
let preKeyBundle = try await makePrekeyRequest(
recipientUniqueId: recipientUniqueId,
serviceId: serviceId,
deviceId: deviceId,
isOnlineMessage: isOnlineMessage,
isTransientSenderKeyDistributionMessage: isTransientSenderKeyDistributionMessage,
sealedSenderParameters: sealedSenderParameters
)
try await SSKEnvironment.shared.databaseStorageRef.awaitableWrite { tx in
try self.createSession(
for: preKeyBundle,
recipientUniqueId: recipientUniqueId,
serviceId: serviceId,
deviceId: deviceId,
transaction: tx
)
}
}
private func makePrekeyRequest(
recipientUniqueId: RecipientUniqueId?,
serviceId: ServiceId,
deviceId: UInt32,
isOnlineMessage: Bool,
isTransientSenderKeyDistributionMessage: Bool,
sealedSenderParameters: SealedSenderParameters?
) async throws -> SignalServiceKit.PreKeyBundle {
Logger.info("serviceId: \(serviceId).\(deviceId)")
// As an optimization, skip the request if an error is guaranteed.
if willDefinitelyHaveUntrustedIdentityError(for: serviceId) {
Logger.info("Skipping prekey request due to untrusted identity.")
throw UntrustedIdentityError(serviceId: serviceId)
}
if let recipientUniqueId, willLikelyHaveInvalidKeySignatureError(for: recipientUniqueId) {
Logger.info("Skipping prekey request due to invalid prekey signature.")
// Check if this error is happening repeatedly for this recipientUniqueId.
// If so, return an InvalidKeySignatureError as a terminal failure.
throw InvalidKeySignatureError(serviceId: serviceId, isTerminalFailure: true)
}
if isOnlineMessage || isTransientSenderKeyDistributionMessage {
Logger.info("Skipping prekey request for transient message")
throw MessageSenderNoSessionForTransientMessageError()
}
var requestOptions: RequestMaker.Options = [.waitForWebSocketToOpen]
// If we're sending a story, we can use the identified connection to fetch
// pre keys and the unidentified connection to send the message. For other
// types of messages, we expect unidentified message sends to fail if we
// can't fetch pre keys via the unidentified connection.
if let sealedSenderParameters, sealedSenderParameters.message.isStorySend {
requestOptions.insert(.allowIdentifiedFallback)
}
let requestMaker = RequestMaker(
label: "Prekey Fetch",
serviceId: serviceId,
canUseStoryAuth: false,
accessKey: sealedSenderParameters?.accessKey,
endorsement: sealedSenderParameters?.endorsement,
authedAccount: .implicit(),
options: requestOptions
)
do {
let result = try await requestMaker.makeRequest {
return OWSRequestFactory.recipientPreKeyRequest(serviceId: serviceId, deviceId: deviceId, auth: $0)
}
guard let responseData = result.response.responseBodyData else {
throw OWSAssertionError("Prekey fetch missing response object.")
}
guard let bundle = try? JSONDecoder().decode(SignalServiceKit.PreKeyBundle.self, from: responseData) else {
throw OWSAssertionError("Prekey fetch returned an invalid bundle.")
}
return bundle
} catch {
switch error.httpStatusCode {
case 404:
throw MessageSenderError.missingDevice
case 429:
throw MessageSenderError.prekeyRateLimit
default:
throw error
}
}
}
private func createSession(
for preKeyBundle: SignalServiceKit.PreKeyBundle,
recipientUniqueId: String,
serviceId: ServiceId,
deviceId: UInt32,
transaction: SDSAnyWriteTransaction
) throws {
assert(!Thread.isMainThread)
if try containsValidSession(for: serviceId, deviceId: deviceId, tx: transaction.asV2Write) {
Logger.warn("Session already exists for \(serviceId), deviceId: \(deviceId).")
return
}
guard let deviceBundle = preKeyBundle.devices.first(where: { $0.deviceId == deviceId }) else {
throw OWSAssertionError("Server didn't provide a bundle for the requested device.")
}
Logger.info("Creating session for \(serviceId), deviceId: \(deviceId); signed \(deviceBundle.signedPreKey.keyId), one-time \(deviceBundle.preKey?.keyId as Optional), kyber \(deviceBundle.pqPreKey?.keyId as Optional)")
let bundle: LibSignalClient.PreKeyBundle
if let preKey = deviceBundle.preKey {
if let pqPreKey = deviceBundle.pqPreKey {
bundle = try LibSignalClient.PreKeyBundle(
registrationId: deviceBundle.registrationId,
deviceId: deviceId,
prekeyId: preKey.keyId,
prekey: preKey.publicKey,
signedPrekeyId: deviceBundle.signedPreKey.keyId,
signedPrekey: deviceBundle.signedPreKey.publicKey,
signedPrekeySignature: deviceBundle.signedPreKey.signature,
identity: preKeyBundle.identityKey,
kyberPrekeyId: pqPreKey.keyId,
kyberPrekey: pqPreKey.publicKey,
kyberPrekeySignature: pqPreKey.signature
)
} else {
bundle = try LibSignalClient.PreKeyBundle(
registrationId: deviceBundle.registrationId,
deviceId: deviceId,
prekeyId: preKey.keyId,
prekey: preKey.publicKey,
signedPrekeyId: deviceBundle.signedPreKey.keyId,
signedPrekey: deviceBundle.signedPreKey.publicKey,
signedPrekeySignature: deviceBundle.signedPreKey.signature,
identity: preKeyBundle.identityKey
)
}
} else {
if let pqPreKey = deviceBundle.pqPreKey {
bundle = try LibSignalClient.PreKeyBundle(
registrationId: deviceBundle.registrationId,
deviceId: deviceId,
signedPrekeyId: deviceBundle.signedPreKey.keyId,
signedPrekey: deviceBundle.signedPreKey.publicKey,
signedPrekeySignature: deviceBundle.signedPreKey.signature,
identity: preKeyBundle.identityKey,
kyberPrekeyId: pqPreKey.keyId,
kyberPrekey: pqPreKey.publicKey,
kyberPrekeySignature: pqPreKey.signature
)
} else {
bundle = try LibSignalClient.PreKeyBundle(
registrationId: deviceBundle.registrationId,
deviceId: deviceId,
signedPrekeyId: deviceBundle.signedPreKey.keyId,
signedPrekey: deviceBundle.signedPreKey.publicKey,
signedPrekeySignature: deviceBundle.signedPreKey.signature,
identity: preKeyBundle.identityKey
)
}
}
do {
let identityManager = DependenciesBridge.shared.identityManager
let protocolAddress = ProtocolAddress(serviceId, deviceId: deviceId)
try processPreKeyBundle(
bundle,
for: protocolAddress,
sessionStore: DependenciesBridge.shared.signalProtocolStoreManager.signalProtocolStore(for: .aci).sessionStore,
identityStore: identityManager.libSignalStore(for: .aci, tx: transaction.asV2Write),
context: transaction
)
} catch SignalError.untrustedIdentity(_), IdentityManagerError.identityKeyMismatchForOutgoingMessage {
Logger.warn("Found untrusted identity for \(serviceId)")
handleUntrustedIdentityKeyError(
serviceId: serviceId,
recipientUniqueId: recipientUniqueId,
preKeyBundle: preKeyBundle,
transaction: transaction
)
throw UntrustedIdentityError(serviceId: serviceId)
} catch SignalError.invalidSignature(_) {
Logger.error("Invalid key signature for \(serviceId)")
// Received this error from the server, so this could either be
// an invalid key due to a broken client, or it may be a random
// corruption in transit. Mark having encountered an error for
// this recipient so later checks can determine if this has happend
// more than once and fail early.
// The error thrown here is considered non-terminal which allows
// the request to be retried.
hadInvalidKeySignatureError(for: recipientUniqueId)
throw InvalidKeySignatureError(serviceId: serviceId, isTerminalFailure: false)
}
owsAssertDebug(try containsValidSession(for: serviceId, deviceId: deviceId, tx: transaction.asV2Write), "Couldn't create session.")
}
// MARK: - Untrusted Identities
private func handleUntrustedIdentityKeyError(
serviceId: ServiceId,
recipientUniqueId: RecipientUniqueId,
preKeyBundle: SignalServiceKit.PreKeyBundle,
transaction tx: SDSAnyWriteTransaction
) {
let identityManager = DependenciesBridge.shared.identityManager
identityManager.saveIdentityKey(preKeyBundle.identityKey, for: serviceId, tx: tx.asV2Write)
}
/// If true, we expect fetching a bundle will fail no matter what it contains.
///
/// If we're noLongerVerified, nothing we fetch can alter the state. The
/// user must manually accept the new identity key and then retry the
/// message.
///
/// If we're implicit & it's not trusted, it means it changed recently. It
/// would work if we waited a few seconds, but we want to surface the error
/// to the user.
///
/// Even though it's only a few seconds, we must not talk to the server in
/// the implicit case because there could be many messages queued up that
/// would all try to fetch their own bundle.
private func willDefinitelyHaveUntrustedIdentityError(for serviceId: ServiceId) -> Bool {
assert(!Thread.isMainThread)
// Prekey rate limits are strict. Therefore, we want to avoid requesting
// prekey bundles that can't be processed. After a prekey request, we might
// not be able to process it if the new identity key isn't trusted.
let identityManager = DependenciesBridge.shared.identityManager
return SSKEnvironment.shared.databaseStorageRef.read { tx in
return identityManager.untrustedIdentityForSending(
to: SignalServiceAddress(serviceId),
untrustedThreshold: nil,
tx: tx.asV2Read
) != nil
}
}
// MARK: - Invalid Signatures
private typealias InvalidSignatureCache = [RecipientUniqueId: InvalidSignatureCacheItem]
private struct InvalidSignatureCacheItem {
let lastErrorDate: Date
let errorCount: UInt32
}
private let invalidKeySignatureCache = AtomicValue(InvalidSignatureCache(), lock: .init())
private func hadInvalidKeySignatureError(for recipientUniqueId: RecipientUniqueId) {
invalidKeySignatureCache.update { cache in
var errorCount: UInt32 = 1
if let mostRecentError = cache[recipientUniqueId] {
errorCount = mostRecentError.errorCount + 1
}
cache[recipientUniqueId] = InvalidSignatureCacheItem(
lastErrorDate: Date(),
errorCount: errorCount
)
}
}
private func willLikelyHaveInvalidKeySignatureError(for recipientUniqueId: RecipientUniqueId) -> Bool {
assert(!Thread.isMainThread)
// Similar to untrusted identity errors, when an invalid signature for a prekey
// is encountered, it will probably be encountered for a while until the
// target client rotates prekeys and hopfully fixes the bad signature.
// To avoid running into prekey rate limits, remember when an error is
// encountered and slow down sending prekey requests for this recipient.
//
// Additionally, there is always a chance of corruption of the prekey
// bundle during data transmission, which would result in an invalid
// signature of an otherwise correct bundle. To handle this rare case,
// don't begin limiting the prekey request until after encounting the
// second bad signature for a particular recipient.
guard let mostRecentError = invalidKeySignatureCache.get()[recipientUniqueId] else {
return false
}
let staleIdentityLifetime: TimeInterval = .minute * 5
guard abs(mostRecentError.lastErrorDate.timeIntervalSinceNow) < staleIdentityLifetime else {
// Error has expired, remove it to reset the count
invalidKeySignatureCache.update { cache in
_ = cache.removeValue(forKey: recipientUniqueId)
}
return false
}
// Let the first error go, only skip starting on the second error
guard mostRecentError.errorCount > 1 else {
return false
}
return true
}
// MARK: - Sending Attachments
public func sendTransientContactSyncAttachment(
dataSource: DataSource,
localThread: TSContactThread
) async throws {
let uploadResult = try await DependenciesBridge.shared.attachmentUploadManager.uploadTransientAttachment(
dataSource: dataSource
)
let message = SSKEnvironment.shared.databaseStorageRef.read { tx in
return OWSSyncContactsMessage(uploadedAttachment: uploadResult, localThread: localThread, tx: tx)
}
let preparedMessage = PreparedOutgoingMessage.preprepared(contactSyncMessage: message)
let result = await Result { try await sendMessage(preparedMessage) }
try result.get()
}
// MARK: - Constructing Message Sends
public func sendMessage(_ preparedOutgoingMessage: PreparedOutgoingMessage) async throws {
await SSKEnvironment.shared.databaseStorageRef.awaitableWrite { tx in
preparedOutgoingMessage.updateAllUnsentRecipientsAsSending(tx: tx)
}
Logger.info("Sending \(preparedOutgoingMessage)")
// We create a PendingTask so we can block on flushing all current message sends.
let pendingTask = pendingTasks.buildPendingTask(label: "Message Send")
defer { pendingTask.complete() }
try await withThrowingTaskGroup(of: Void.self) { taskGroup in
let uploadOperations = SSKEnvironment.shared.databaseStorageRef.read { tx in
preparedOutgoingMessage.attachmentUploadOperations(tx: tx)
}
for uploadOperation in uploadOperations {
taskGroup.addTask {
try await Upload.uploadQueue.run(uploadOperation)
}
}
try await taskGroup.waitForAll()
}
try await preparedOutgoingMessage.send(self.sendPreparedMessage(_:))
}
private func waitForPreKeyRotationIfNeeded() async throws {
while let taskToWaitFor = preKeyRotationTaskIfNeeded() {
try await taskToWaitFor.value
}
}
private let pendingPreKeyRotation = AtomicValue<Task<Void, Error>?>(nil, lock: .init())
private func preKeyRotationTaskIfNeeded() -> Task<Void, Error>? {
return pendingPreKeyRotation.map { existingTask in
if let existingTask {
return existingTask
}
let shouldRunPreKeyRotation = SSKEnvironment.shared.databaseStorageRef.read { tx in
preKeyManager.isAppLockedDueToPreKeyUpdateFailures(tx: tx.asV2Read)
}
if shouldRunPreKeyRotation {
Logger.info("Rotating signed pre-key before sending message.")
// Retry prekey update every time user tries to send a message while app is
// disabled due to prekey update failures.
//
// Only try to update the signed prekey; updating it is sufficient to
// re-enable message sending.
return Task {
try await self.preKeyManager.rotateSignedPreKeys().value
self.pendingPreKeyRotation.set(nil)
}
}
return nil
}
}
// Mark skipped recipients as such. We may skip because:
//
// * A recipient is no longer in the group.
// * A recipient is blocked.
// * A recipient is unregistered.
// * A recipient does not have the required capability.
private func markSkippedRecipients(
of message: TSOutgoingMessage,
sendingRecipients: [ServiceId],
tx: SDSAnyWriteTransaction
) {
let skippedRecipients = Set(message.sendingRecipientAddresses())
.subtracting(sendingRecipients.lazy.map { SignalServiceAddress($0) })
for address in skippedRecipients {
// Mark this recipient as "skipped".
message.updateWithSkippedRecipient(address, transaction: tx)
}
}
private func unsentRecipients(
of message: TSOutgoingMessage,
in thread: TSThread,
localIdentifiers: LocalIdentifiers,
tx: SDSAnyReadTransaction
) throws -> [SignalServiceAddress] {
if message.isSyncMessage {
return [localIdentifiers.aciAddress]
}
if let groupThread = thread as? TSGroupThread {
// Send to the intersection of:
//
// * "sending" recipients of the message.
// * members of the group.
//
// I.e. try to send a message IFF:
//
// * The recipient was in the group when the message was first tried to be sent.
// * The recipient is still in the group.
// * The recipient is in the "sending" state.
var recipientAddresses = Set<SignalServiceAddress>()
recipientAddresses.formUnion(message.sendingRecipientAddresses())
// Only send to members in the latest known group member list.
// If a member has left the group since this message was enqueued,
// they should not receive the message.
let groupMembership = groupThread.groupModel.groupMembership
var currentValidRecipients = groupMembership.fullMembers
// ...or latest known list of "additional recipients".
//
// This is used to send group update messages for v2 groups to
// pending members who are not included in .sendingRecipientAddresses().
if GroupManager.shouldMessageHaveAdditionalRecipients(message, groupThread: groupThread) {
currentValidRecipients.formUnion(groupMembership.invitedMembers)
}
currentValidRecipients.remove(localIdentifiers.aciAddress)
recipientAddresses.formIntersection(currentValidRecipients)
let blockedAddresses = SSKEnvironment.shared.blockingManagerRef.blockedAddresses(transaction: tx)
recipientAddresses.subtract(blockedAddresses)
return Array(recipientAddresses)
} else if let contactAddress = (thread as? TSContactThread)?.contactAddress {
// Treat 1:1 sends to blocked contacts as failures.
// If we block a user, don't send 1:1 messages to them. The UI
// should prevent this from occurring, but in some edge cases
// you might, for example, have a pending outgoing message when
// you block them.
if SSKEnvironment.shared.blockingManagerRef.isAddressBlocked(contactAddress, transaction: tx) {
Logger.info("Skipping 1:1 send to blocked contact: \(contactAddress).")
throw MessageSenderError.blockedContactRecipient
} else {
return [contactAddress]
}
} else {
// Send to the intersection of:
//
// * "sending" recipients of the message.
// * recipients of the thread
//
// I.e. try to send a message IFF:
//
// * The recipient was part of the thread when the message was first tried to be sent.
// * The recipient is still part of the thread.
// * The recipient is in the "sending" state.
var recipientAddresses = Set(message.sendingRecipientAddresses())
// Only send to members in the latest known thread recipients list.
let currentValidThreadRecipients = thread.recipientAddresses(with: tx)
recipientAddresses.formIntersection(currentValidThreadRecipients)
let blockedAddresses = SSKEnvironment.shared.blockingManagerRef.blockedAddresses(transaction: tx)
recipientAddresses.subtract(blockedAddresses)
if recipientAddresses.contains(localIdentifiers.aciAddress) {
owsFailDebug("Message send recipients should not include self.")
}
return Array(recipientAddresses)
}
}
private static func partitionAddresses(_ addresses: [SignalServiceAddress]) -> ([ServiceId], [E164]) {
var serviceIds = [ServiceId]()
var phoneNumbers = [E164]()
for address in addresses {
if let serviceId = address.serviceId {
serviceIds.append(serviceId)
} else if let phoneNumber = address.e164 {
phoneNumbers.append(phoneNumber)
} else {
owsFailDebug("Recipient has neither ServiceId nor E164.")
}
}
return (serviceIds, phoneNumbers)
}
private func lookUpPhoneNumbers(_ phoneNumbers: [E164]) async throws {
_ = try await SSKEnvironment.shared.contactDiscoveryManagerRef.lookUp(
phoneNumbers: Set(phoneNumbers.lazy.map { $0.stringValue }),
mode: .outgoingMessage
)
}
private func areAttachmentsUploadedWithSneakyTransaction(for message: TSOutgoingMessage) -> Bool {
if message.shouldBeSaved == false {
// Unsaved attachments come in two types:
// * no attachments
// * contact sync, already-uploaded attachment required on init
// So checking for upload state for unsaved attachments is pointless
// (and will, in fact, fail, because of foreign key constraints).
return true
}
return SSKEnvironment.shared.databaseStorageRef.read { tx in
for attachment in message.allAttachments(transaction: tx) {
guard attachment.isUploadedToTransitTier else {
return false
}
}
return true
}
}
private func sendPreparedMessage(_ message: TSOutgoingMessage) async throws {
if !areAttachmentsUploadedWithSneakyTransaction(for: message) {
throw OWSUnretryableMessageSenderError()
}
if DependenciesBridge.shared.appExpiry.isExpired {
throw AppExpiredError()
}
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered.negated {
throw AppDeregisteredError()
}
if message.shouldBeSaved {
let latestCopy = SSKEnvironment.shared.databaseStorageRef.read { tx in
TSInteraction.anyFetch(uniqueId: message.uniqueId, transaction: tx) as? TSOutgoingMessage
}
guard let latestCopy, latestCopy.wasRemotelyDeleted.negated else {
throw MessageDeletedBeforeSentError()
}
}
if DebugFlags.messageSendsFail.get() {
throw OWSUnretryableMessageSenderError()
}
do {
try await waitForPreKeyRotationIfNeeded()
let senderCertificates = try await SSKEnvironment.shared.udManagerRef.fetchSenderCertificates(certificateExpirationPolicy: .permissive)
try await sendPreparedMessage(
message,
recoveryState: OuterRecoveryState(),
senderCertificates: senderCertificates
)
} catch {
if message.wasSentToAnyRecipient {
// Always ignore the sync error...
try? await handleMessageSentLocally(message)
}
// ...so that we can throw the original error for the caller. (Note that we
// throw this error even if the sync message is sent successfully.)
throw error
}
try await handleMessageSentLocally(message)
}
private enum SendMessageNextAction {
/// Look up missing phone numbers & then try sending again.
case lookUpPhoneNumbersAndTryAgain([E164])
/// Fetch a new set of GSEs & then try sending again.
case fetchGroupSendEndorsementsAndTryAgain(GroupSecretParams)
/// Perform the `sendPreparedMessage` step.
case sendPreparedMessage(PreparedState)
struct PreparedState {
let serializedMessage: SerializedMessage
let thread: TSThread
let fanoutRecipients: [ServiceId]
let sendViaSenderKey: (@Sendable () async -> [(ServiceId, any Error)])?
let senderCertificate: SenderCertificate
let udAccess: [ServiceId: OWSUDAccess]
let endorsements: GroupSendEndorsements?
let localIdentifiers: LocalIdentifiers
}
}
/// Certain errors are "correctable" and result in immediate retries. For
/// example, if there's a newly-added device, we should encrypt the message
/// for that device and try to send it immediately. However, some of these
/// errors can *theoretically* happen ad nauseam (but they shouldn't). To
/// avoid tight retry loops, we handle them immediately just once and then
/// use the standard retry logic if they happen repeatedly.
private struct OuterRecoveryState {
var canLookUpPhoneNumbers = true
var canRefreshExpiringGroupSendEndorsements = true
// Sender key sends will fail if a single recipient has an invalid access
// token, but the server can't identify the recipient for us. To recover,
// fall back to a fanout; this will fail only for the affect recipient.
var canUseMultiRecipientSealedSender = true
var canHandleMultiRecipientMismatchedDevices = true
var canHandleMultiRecipientStaleDevices = true
func mutated(_ block: (inout Self) -> Void) -> Self {
var mutableSelf = self
block(&mutableSelf)
return mutableSelf
}
}
private func sendPreparedMessage(
_ message: TSOutgoingMessage,
recoveryState: OuterRecoveryState,
senderCertificates: SenderCertificates
) async throws {
let nextAction: SendMessageNextAction? = try await SSKEnvironment.shared.databaseStorageRef.awaitableWrite { tx in
guard let thread = message.thread(tx: tx) else {
throw MessageSenderError.threadMissing
}
let canSendToThread: Bool = {
if message is OWSOutgoingReactionMessage {
return thread.canSendReactionToThread
}
let isChatMessage = (
(
message.shouldBeSaved
&& message.insertedMessageHasRenderableContent(rowId: message.sqliteRowId!, tx: tx)
)
|| message is OutgoingGroupCallUpdateMessage
|| message is OWSOutgoingCallMessage
)
return isChatMessage ? thread.canSendChatMessagesToThread() : thread.canSendNonChatMessagesToThread
}()
guard canSendToThread else {
if message.shouldBeSaved {
throw OWSAssertionError("Sending to thread blocked.")
}
// Pretend to succeed for non-visible messages like read receipts, etc.
return nil
}
let tsAccountManager = DependenciesBridge.shared.tsAccountManager
guard let localIdentifiers = tsAccountManager.localIdentifiers(tx: tx.asV2Read) else {
throw OWSAssertionError("Not registered.")
}
let proposedAddresses = try self.unsentRecipients(of: message, in: thread, localIdentifiers: localIdentifiers, tx: tx)
let (serviceIds, phoneNumbersToFetch) = Self.partitionAddresses(proposedAddresses)
// If we haven't yet tried to look up phone numbers, send an asynchronous
// request to look up phone numbers, and then try to go through this logic
// *again* in a new transaction. Things may change for that subsequent
// attempt, and if there's still missing phone numbers at that point, we'll
// skip them for this message.
if recoveryState.canLookUpPhoneNumbers, !phoneNumbersToFetch.isEmpty {
return .lookUpPhoneNumbersAndTryAgain(phoneNumbersToFetch)
}
self.markSkippedRecipients(of: message, sendingRecipients: serviceIds, tx: tx)
if let contactThread = thread as? TSContactThread {
// In the "self-send" aka "Note to Self" special case, we only need to send
// certain kinds of messages. (In particular, regular data messages are
// sent via their implicit sync message only.)
if contactThread.contactAddress.isLocalAddress, !message.canSendToLocalAddress {
owsAssertDebug(serviceIds.count == 1)
Logger.info("Dropping \(type(of: message)) sent to local address (it should be sent by sync message)")
// Don't mark self-sent messages as read (or sent) until the sync transcript is sent.
return nil
}
}
if serviceIds.isEmpty {
// All recipients are already sent or can be skipped. NOTE: We might still
// need to send a sync transcript.
return nil
}
guard let serializedMessage = self.buildAndRecordMessage(message, in: thread, tx: tx) else {
throw OWSAssertionError("Couldn't build message.")
}
let senderCertificate: SenderCertificate = {
switch SSKEnvironment.shared.udManagerRef.phoneNumberSharingMode(tx: tx.asV2Read).orDefault {
case .everybody:
return senderCertificates.defaultCert
case .nobody:
return senderCertificates.uuidOnlyCert
}
}()
let udAccessMap = self.fetchSealedSenderAccess(
for: serviceIds,
message: message,
senderCertificate: senderCertificate,
localIdentifiers: localIdentifiers,
tx: tx
)
let endorsements: GroupSendEndorsements?
do {
if let secretParams = try? ((thread as? TSGroupThread)?.groupModel as? TSGroupModelV2)?.secretParams() {
let threadId = thread.sqliteRowId!
endorsements = try fetchEndorsements(forThreadId: threadId, secretParams: secretParams, tx: tx.asV2Read)
if
recoveryState.canRefreshExpiringGroupSendEndorsements,
endorsements == nil || endorsements!.expiration.timeIntervalSinceNow < 2 * .hour
{
Logger.warn("Refetching GSEs for \(thread.uniqueId) that are missing or about to expire.")
return .fetchGroupSendEndorsementsAndTryAgain(secretParams)
}
} else {
endorsements = nil
}
} catch {
owsFailDebug("Continuing without GSEs that couldn't be fetched: \(error)")
endorsements = nil
}
let senderKeyRecipients: [ServiceId]
let sendViaSenderKey: (@Sendable () async -> [(ServiceId, any Error)])?
if recoveryState.canUseMultiRecipientSealedSender, thread.usesSenderKey {
(senderKeyRecipients, sendViaSenderKey) = self.prepareSenderKeyMessageSend(
for: serviceIds,
in: thread,
message: message,
serializedMessage: serializedMessage,
endorsements: endorsements,
udAccessMap: udAccessMap,
senderCertificate: senderCertificate,
localIdentifiers: localIdentifiers,
tx: tx
)
} else {
senderKeyRecipients = []
sendViaSenderKey = nil
}
if thread is TSGroupThread, sendViaSenderKey == nil, serviceIds.count >= 2 {
let notificationPresenter = SSKEnvironment.shared.notificationPresenterRef
notificationPresenter.notifyTestPopulation(ofErrorMessage: "Couldn't send using GSEs.")
}
return .sendPreparedMessage(SendMessageNextAction.PreparedState(
serializedMessage: serializedMessage,
thread: thread,
fanoutRecipients: Array(Set(serviceIds).subtracting(senderKeyRecipients)),
sendViaSenderKey: sendViaSenderKey,
senderCertificate: senderCertificate,
udAccess: udAccessMap,
endorsements: endorsements,
localIdentifiers: localIdentifiers
))
}
let retryRecoveryState: OuterRecoveryState
switch nextAction {
case .none:
return
case .lookUpPhoneNumbersAndTryAgain(let phoneNumbers):
try await lookUpPhoneNumbers(phoneNumbers)
retryRecoveryState = recoveryState.mutated({ $0.canLookUpPhoneNumbers = false })
case .fetchGroupSendEndorsementsAndTryAgain(let secretParams):
do {
try await SSKEnvironment.shared.groupV2UpdatesRef.refreshGroup(secretParams: secretParams)
} catch {
let groupId = try secretParams.getPublicParams().getGroupIdentifier()
Logger.warn("Couldn't refresh \(groupId.logString) to fetch GSEs: \(error)")
// continue anyways... we'll fall back to a fanout when retrying
}
retryRecoveryState = recoveryState.mutated({ $0.canRefreshExpiringGroupSendEndorsements = false })
case .sendPreparedMessage(let state):
let perRecipientErrors = await sendPreparedMessage(
message: message,
serializedMessage: state.serializedMessage,
in: state.thread,
viaFanoutTo: state.fanoutRecipients,
viaSenderKey: state.sendViaSenderKey,
senderCertificate: state.senderCertificate,
udAccess: state.udAccess,
endorsements: state.endorsements,
localIdentifiers: state.localIdentifiers
)
let recipientErrors = MessageSenderRecipientErrors(recipientErrors: perRecipientErrors)
if recipientErrors.containsAny(of: .invalidAuthHeader) {
retryRecoveryState = recoveryState.mutated({ $0.canUseMultiRecipientSealedSender = false })
break
}
if recoveryState.canHandleMultiRecipientMismatchedDevices, recipientErrors.containsAny(of: .deviceUpdate) {
retryRecoveryState = recoveryState.mutated({ $0.canHandleMultiRecipientMismatchedDevices = false })
break
}
if recoveryState.canHandleMultiRecipientStaleDevices, recipientErrors.containsAny(of: .staleDevices) {
retryRecoveryState = recoveryState.mutated({ $0.canHandleMultiRecipientStaleDevices = false })
break
}
if !perRecipientErrors.isEmpty {
try await handleSendFailure(message: message, thread: state.thread, perRecipientErrors: perRecipientErrors)
}
return
}
try await sendPreparedMessage(
message,
recoveryState: retryRecoveryState,
senderCertificates: senderCertificates
)
}
private func sendPreparedMessage(
message: TSOutgoingMessage,
serializedMessage: SerializedMessage,
in thread: TSThread,
viaFanoutTo fanoutRecipients: [ServiceId],
viaSenderKey sendViaSenderKey: (@Sendable () async -> [(ServiceId, any Error)])?,
senderCertificate: SenderCertificate,
udAccess sendingAccessMap: [ServiceId: OWSUDAccess],
endorsements: GroupSendEndorsements?,
localIdentifiers: LocalIdentifiers
) async -> [(ServiceId, any Error)] {
// Both types are Arrays because Sender Key Tasks may return N errors when
// sending to N participants. (Fanout Tasks always send to one recipient
// and will therefore return either no error or exactly one error.)
return await withTaskGroup(
of: [(ServiceId, any Error)].self,
returning: [(ServiceId, any Error)].self
) { taskGroup in
if let sendViaSenderKey {
taskGroup.addTask(operation: sendViaSenderKey)
}
// Perform an "OWSMessageSend" for each non-senderKey recipient.
for serviceId in fanoutRecipients {
let messageSend = OWSMessageSend(
message: message,
plaintextContent: serializedMessage.plaintextData,
plaintextPayloadId: serializedMessage.payloadId,
thread: thread,
serviceId: serviceId,
localIdentifiers: localIdentifiers
)
var sealedSenderParameters = SealedSenderParameters(
message: message,
senderCertificate: senderCertificate,
accessKey: sendingAccessMap[serviceId],
endorsement: endorsements?.tokenBuilder(forServiceId: serviceId)
)
if localIdentifiers.contains(serviceId: serviceId) {
owsAssertDebug(sealedSenderParameters == nil, "Can't use Sealed Sender for ourselves.")
sealedSenderParameters = nil
}
taskGroup.addTask {
do {
try await self.performMessageSend(messageSend, sealedSenderParameters: sealedSenderParameters)
return []
} catch {
return [(messageSend.serviceId, error)]
}
}
}
return await taskGroup.reduce(into: [], { $0.append(contentsOf: $1) })
}
}
private func fetchSealedSenderAccess(
for serviceIds: [ServiceId],
message: TSOutgoingMessage,
senderCertificate: SenderCertificate,
localIdentifiers: LocalIdentifiers,
tx: SDSAnyReadTransaction
) -> [ServiceId: OWSUDAccess] {
if DebugFlags.disableUD.get() {
return [:]
}
var result = [ServiceId: OWSUDAccess]()
for serviceId in serviceIds {
if localIdentifiers.contains(serviceId: serviceId) {
continue
}
result[serviceId] = SSKEnvironment.shared.udManagerRef.udAccess(for: serviceId, tx: tx)
}
return result
}
private func fetchEndorsements(forThreadId threadId: Int64, secretParams: GroupSecretParams, tx: any DBReadTransaction) throws -> GroupSendEndorsements? {
let combinedRecord = try groupSendEndorsementStore.fetchCombinedEndorsement(groupThreadId: threadId, tx: tx)
guard let combinedRecord else {
return nil
}
let combinedEndorsement = try GroupSendEndorsement(contents: [UInt8](combinedRecord.endorsement))
var individualEndorsements = [ServiceId: GroupSendEndorsement]()
for record in try groupSendEndorsementStore.fetchIndividualEndorsements(groupThreadId: threadId, tx: tx) {
let endorsement = try GroupSendEndorsement(contents: [UInt8](record.endorsement))
let recipient = DependenciesBridge.shared.recipientDatabaseTable.fetchRecipient(rowId: record.recipientId, tx: tx)
guard let recipient else {
throw OWSAssertionError("Missing Recipient that must exist.")
}
guard let serviceId = recipient.aci ?? recipient.pni else {
throw OWSAssertionError("Missing ServiceId that must exist.")
}